perf.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include "perf.h"
  2. #include "probes.h"
  3. #include <util/system/datetime.h>
  4. #include <util/system/hp_timer.h>
  5. namespace NLWTrace {
  6. LWTRACE_USING(LWTRACE_INTERNAL_PROVIDER);
  7. TCpuTracker::TCpuTracker()
  8. : MinReportPeriod(NHPTimer::GetCyclesPerSecond())
  9. {
  10. ResetStats();
  11. }
  12. void TCpuTracker::Enter() {
  13. LastTs = GetCycleCount();
  14. }
  15. void TCpuTracker::Exit(const TProbe* probe) {
  16. ui64 exitTs = GetCycleCount();
  17. if (exitTs < LastTs) {
  18. return; // probably TSC was reset
  19. }
  20. ui64 cycles = exitTs - LastTs;
  21. LastTs = exitTs;
  22. AddStats(probe, cycles);
  23. }
  24. void TCpuTracker::AddStats(const TProbe* probe, ui64 cycles) {
  25. if (MaxCycles < cycles) {
  26. MaxProbe = probe;
  27. MaxCycles = cycles;
  28. }
  29. if (MinCycles > cycles) {
  30. MinCycles = cycles;
  31. }
  32. ProbeCycles += cycles;
  33. Count++;
  34. if (LastTs - LastReportTs > MinReportPeriod) {
  35. Report();
  36. }
  37. }
  38. void TCpuTracker::ResetStats() {
  39. MaxCycles = 0;
  40. MaxProbe = nullptr;
  41. MinCycles = ui64(-1);
  42. ProbeCycles = 0;
  43. Count = 0;
  44. }
  45. void TCpuTracker::Report() {
  46. if (!Reporting) {
  47. Reporting = true;
  48. ReportNotReentrant();
  49. Reporting = false;
  50. }
  51. }
  52. void TCpuTracker::ReportNotReentrant() {
  53. if (LastReportTs && Count > 0 && LastTs > LastReportTs) {
  54. ui64 reportPeriod = LastTs - LastReportTs;
  55. double share = double(ProbeCycles) / reportPeriod;
  56. double minMs = MilliSeconds(MinCycles);
  57. double maxMs = MilliSeconds(MaxCycles);
  58. double avgMs = MilliSeconds(ProbeCycles) / Count;
  59. LastReportTs = LastTs;
  60. ResetStats();
  61. LWPROBE(PerfReport, share, minMs, maxMs, avgMs);
  62. } else {
  63. LastReportTs = LastTs;
  64. ResetStats();
  65. }
  66. }
  67. double TCpuTracker::MilliSeconds(ui64 cycles) {
  68. return NHPTimer::GetSeconds(cycles) * 1000.0;
  69. }
  70. }