Profiler.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Diagnostics;
  3. using MediaBrowser.Common.Logging;
  4. using MediaBrowser.Model.Logging;
  5. namespace MediaBrowser.Controller.Library
  6. {
  7. /// <summary>
  8. /// Class Profiler
  9. /// </summary>
  10. public class Profiler : IDisposable
  11. {
  12. /// <summary>
  13. /// The name
  14. /// </summary>
  15. readonly string name;
  16. /// <summary>
  17. /// The stopwatch
  18. /// </summary>
  19. readonly Stopwatch stopwatch;
  20. /// <summary>
  21. /// The _logger
  22. /// </summary>
  23. private ILogger _logger;
  24. /// <summary>
  25. /// Initializes a new instance of the <see cref="Profiler" /> class.
  26. /// </summary>
  27. /// <param name="name">The name.</param>
  28. /// <param name="logger">The logger.</param>
  29. public Profiler(string name, ILogger logger)
  30. {
  31. this.name = name;
  32. _logger = logger;
  33. stopwatch = new Stopwatch();
  34. stopwatch.Start();
  35. }
  36. #region IDisposable Members
  37. /// <summary>
  38. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  39. /// </summary>
  40. public void Dispose()
  41. {
  42. Dispose(true);
  43. GC.SuppressFinalize(this);
  44. }
  45. /// <summary>
  46. /// Releases unmanaged and - optionally - managed resources.
  47. /// </summary>
  48. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  49. protected virtual void Dispose(bool dispose)
  50. {
  51. if (dispose)
  52. {
  53. stopwatch.Stop();
  54. string message;
  55. if (stopwatch.ElapsedMilliseconds > 300000)
  56. {
  57. message = string.Format("{0} took {1} minutes.",
  58. name, ((float)stopwatch.ElapsedMilliseconds / 60000).ToString("F"));
  59. }
  60. else
  61. {
  62. message = string.Format("{0} took {1} seconds.",
  63. name, ((float)stopwatch.ElapsedMilliseconds / 1000).ToString("#0.000"));
  64. }
  65. _logger.Info(message);
  66. }
  67. }
  68. #endregion
  69. }
  70. }