Profiler.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Diagnostics;
  3. using System.Globalization;
  4. using Microsoft.Extensions.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 readonly ILogger<Profiler> _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<Profiler> logger)
  30. {
  31. this._name = name;
  32. _logger = logger;
  33. _stopwatch = new Stopwatch();
  34. _stopwatch.Start();
  35. }
  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. GC.SuppressFinalize(this);
  43. }
  44. /// <summary>
  45. /// Releases unmanaged and - optionally - managed resources.
  46. /// </summary>
  47. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  48. protected virtual void Dispose(bool dispose)
  49. {
  50. if (dispose)
  51. {
  52. _stopwatch.Stop();
  53. string message;
  54. if (_stopwatch.ElapsedMilliseconds > 300000)
  55. {
  56. message = string.Format(
  57. CultureInfo.InvariantCulture,
  58. "{0} took {1} minutes.",
  59. _name,
  60. ((float)_stopwatch.ElapsedMilliseconds / 60000).ToString("F", CultureInfo.InvariantCulture));
  61. }
  62. else
  63. {
  64. message = string.Format(
  65. CultureInfo.InvariantCulture,
  66. "{0} took {1} seconds.",
  67. _name,
  68. ((float)_stopwatch.ElapsedMilliseconds / 1000).ToString("#0.000", CultureInfo.InvariantCulture));
  69. }
  70. _logger.LogInformation(message);
  71. }
  72. }
  73. }
  74. }