Statistics.cs 2.1 KB

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