Statistics.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Text;
  7. namespace ARMeilleure
  8. {
  9. public static class Statistics
  10. {
  11. private const int ReportMaxFunctions = 100;
  12. [ThreadStatic]
  13. private static Stopwatch _executionTimer;
  14. private static ConcurrentDictionary<ulong, long> _ticksPerFunction;
  15. static Statistics()
  16. {
  17. _ticksPerFunction = new ConcurrentDictionary<ulong, long>();
  18. }
  19. public static void InitializeTimer()
  20. {
  21. #if M_PROFILE
  22. if (_executionTimer == null)
  23. {
  24. _executionTimer = new Stopwatch();
  25. }
  26. #endif
  27. }
  28. internal static void StartTimer()
  29. {
  30. #if M_PROFILE
  31. _executionTimer.Restart();
  32. #endif
  33. }
  34. internal static void StopTimer(ulong funcAddr)
  35. {
  36. #if M_PROFILE
  37. _executionTimer.Stop();
  38. long ticks = _executionTimer.ElapsedTicks;
  39. _ticksPerFunction.AddOrUpdate(funcAddr, ticks, (key, oldTicks) => oldTicks + ticks);
  40. #endif
  41. }
  42. internal static void ResumeTimer()
  43. {
  44. #if M_PROFILE
  45. _executionTimer.Start();
  46. #endif
  47. }
  48. internal static void PauseTimer()
  49. {
  50. #if M_PROFILE
  51. _executionTimer.Stop();
  52. #endif
  53. }
  54. public static string GetReport()
  55. {
  56. int count = 0;
  57. StringBuilder sb = new StringBuilder();
  58. sb.AppendLine(" Function address | Time");
  59. sb.AppendLine("--------------------------");
  60. KeyValuePair<ulong, long>[] funcTable = _ticksPerFunction.ToArray();
  61. foreach (KeyValuePair<ulong, long> kv in funcTable.OrderByDescending(x => x.Value))
  62. {
  63. long timeInMs = (kv.Value * 1000) / Stopwatch.Frequency;
  64. sb.AppendLine($" 0x{kv.Key:X16} | {timeInMs} ms");
  65. if (count++ >= ReportMaxFunctions)
  66. {
  67. break;
  68. }
  69. }
  70. return sb.ToString();
  71. }
  72. }
  73. }