PerformanceStatistics.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using MoonSharp.Interpreter.Diagnostics.PerformanceCounters;
  6. namespace MoonSharp.Interpreter.Diagnostics
  7. {
  8. /// <summary>
  9. /// A single object of this type exists for every script and gives access to performance statistics.
  10. /// </summary>
  11. public class PerformanceStatistics
  12. {
  13. IPerformanceStopwatch[] m_Stopwatches = new IPerformanceStopwatch[(int)PerformanceCounter.LastValue];
  14. static IPerformanceStopwatch[] m_GlobalStopwatches = new IPerformanceStopwatch[(int)PerformanceCounter.LastValue];
  15. static PerformanceStatistics()
  16. {
  17. m_GlobalStopwatches[(int)PerformanceCounter.AdaptersCompilation] = new GlobalPerformanceStopwatch(PerformanceCounter.AdaptersCompilation);
  18. }
  19. internal PerformanceStatistics()
  20. {
  21. for (int i = 0; i < (int)PerformanceCounter.LastValue; i++)
  22. m_Stopwatches[i] = m_GlobalStopwatches[i] ?? new PerformanceStopwatch((PerformanceCounter)i);
  23. }
  24. /// <summary>
  25. /// Gets the result of the specified performance counter .
  26. /// </summary>
  27. /// <param name="pc">The PerformanceCounter.</param>
  28. /// <returns></returns>
  29. public PerformanceResult GetPerformanceCounterResult(PerformanceCounter pc)
  30. {
  31. return m_Stopwatches[(int)pc].GetResult();
  32. }
  33. /// <summary>
  34. /// Starts a stopwatch.
  35. /// </summary>
  36. /// <returns></returns>
  37. internal IDisposable StartStopwatch(PerformanceCounter pc)
  38. {
  39. return m_Stopwatches[(int)pc].Start();
  40. }
  41. /// <summary>
  42. /// Starts a stopwatch.
  43. /// </summary>
  44. /// <returns></returns>
  45. internal static IDisposable StartGlobalStopwatch(PerformanceCounter pc)
  46. {
  47. return m_GlobalStopwatches[(int)pc].Start();
  48. }
  49. /// <summary>
  50. /// Gets a string with a complete performance log.
  51. /// </summary>
  52. /// <returns></returns>
  53. public string GetPerformanceLog()
  54. {
  55. StringBuilder sb = new StringBuilder();
  56. for (int i = 0; i < (int)PerformanceCounter.LastValue; i++)
  57. sb.AppendLine(this.GetPerformanceCounterResult((PerformanceCounter)i).ToString());
  58. return sb.ToString();
  59. }
  60. }
  61. }