Profiler.cs 2.2 KB

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