Profiler.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. /// <summary>
  36. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  37. /// </summary>
  38. public void Dispose()
  39. {
  40. Dispose(true);
  41. }
  42. /// <summary>
  43. /// Releases unmanaged and - optionally - managed resources.
  44. /// </summary>
  45. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  46. protected virtual void Dispose(bool dispose)
  47. {
  48. if (dispose)
  49. {
  50. _stopwatch.Stop();
  51. string message;
  52. if (_stopwatch.ElapsedMilliseconds > 300000)
  53. {
  54. message = string.Format("{0} took {1} minutes.",
  55. _name, ((float)_stopwatch.ElapsedMilliseconds / 60000).ToString("F"));
  56. }
  57. else
  58. {
  59. message = string.Format("{0} took {1} seconds.",
  60. _name, ((float)_stopwatch.ElapsedMilliseconds / 1000).ToString("#0.000"));
  61. }
  62. _logger.LogInformation(message);
  63. }
  64. }
  65. }
  66. }