Profiler.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #nullable disable
  2. using System;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using Microsoft.Extensions.Logging;
  6. namespace MediaBrowser.Controller.Library
  7. {
  8. /// <summary>
  9. /// Class Profiler.
  10. /// </summary>
  11. public class Profiler : IDisposable
  12. {
  13. /// <summary>
  14. /// The name.
  15. /// </summary>
  16. private readonly string _name;
  17. /// <summary>
  18. /// The stopwatch.
  19. /// </summary>
  20. private readonly Stopwatch _stopwatch;
  21. /// <summary>
  22. /// The _logger.
  23. /// </summary>
  24. private readonly ILogger<Profiler> _logger;
  25. /// <summary>
  26. /// Initializes a new instance of the <see cref="Profiler" /> class.
  27. /// </summary>
  28. /// <param name="name">The name.</param>
  29. /// <param name="logger">The logger.</param>
  30. public Profiler(string name, ILogger<Profiler> logger)
  31. {
  32. this._name = name;
  33. _logger = logger;
  34. _stopwatch = new Stopwatch();
  35. _stopwatch.Start();
  36. }
  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(
  58. CultureInfo.InvariantCulture,
  59. "{0} took {1} minutes.",
  60. _name,
  61. ((float)_stopwatch.ElapsedMilliseconds / 60000).ToString("F", CultureInfo.InvariantCulture));
  62. }
  63. else
  64. {
  65. message = string.Format(
  66. CultureInfo.InvariantCulture,
  67. "{0} took {1} seconds.",
  68. _name,
  69. ((float)_stopwatch.ElapsedMilliseconds / 1000).ToString("#0.000", CultureInfo.InvariantCulture));
  70. }
  71. _logger.LogInformation(message);
  72. }
  73. }
  74. }
  75. }