cputimer.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. #pragma once
  2. #include "base.h"
  3. #include <util/system/rusage.h>
  4. #include <util/generic/string.h>
  5. #include <util/stream/str.h>
  6. class TTimer {
  7. private:
  8. TInstant Start_;
  9. TStringStream Message_;
  10. public:
  11. TTimer(const TStringBuf message = TStringBuf(" took: "));
  12. ~TTimer();
  13. };
  14. class TSimpleTimer {
  15. TInstant T;
  16. public:
  17. TSimpleTimer() {
  18. Reset();
  19. }
  20. TDuration Get() const {
  21. return TInstant::Now() - T;
  22. }
  23. void Reset() {
  24. T = TInstant::Now();
  25. }
  26. };
  27. class TProfileTimer {
  28. TDuration T;
  29. public:
  30. TProfileTimer() {
  31. Reset();
  32. }
  33. TDuration Get() const {
  34. return TRusage::Get().Utime - T;
  35. }
  36. TDuration Step() {
  37. TRusage r;
  38. r.Fill();
  39. TDuration d = r.Utime - T;
  40. T = r.Utime;
  41. return d;
  42. }
  43. void Reset() {
  44. T = TRusage::Get().Utime;
  45. }
  46. };
  47. /// Return cached processor cycle count per second. Method takes 1 second at first invocation.
  48. /// Note, on older systems cycle rate may change during program lifetime,
  49. /// so returned value may be incorrect. Modern Intel and AMD processors keep constant TSC rate.
  50. ui64 GetCyclesPerMillisecond();
  51. void SetCyclesPerSecond(ui64 cycles);
  52. TDuration CyclesToDuration(ui64 cycles);
  53. ui64 DurationToCycles(TDuration duration);
  54. class TPrecisionTimer {
  55. private:
  56. ui64 Start = 0;
  57. public:
  58. TPrecisionTimer();
  59. ui64 GetCycleCount() const;
  60. };
  61. TString FormatCycles(ui64 cycles);
  62. class TFormattedPrecisionTimer {
  63. private:
  64. ui64 Start;
  65. const char* Message;
  66. IOutputStream* Out;
  67. public:
  68. TFormattedPrecisionTimer(const char* message = "took ", IOutputStream* out = &Cout);
  69. ~TFormattedPrecisionTimer();
  70. };
  71. class TFuncTimer {
  72. public:
  73. TFuncTimer(const char* func);
  74. ~TFuncTimer();
  75. private:
  76. const TInstant Start_;
  77. const char* Func_;
  78. };
  79. class TFakeTimer {
  80. public:
  81. inline TFakeTimer(const char* = nullptr) noexcept {
  82. }
  83. };
  84. #if defined(WITH_DEBUG)
  85. #define TDebugTimer TFuncTimer
  86. #else
  87. #define TDebugTimer TFakeTimer
  88. #endif
  89. class TTimeLogger {
  90. private:
  91. TString Message;
  92. bool Verbose;
  93. bool OK;
  94. time_t Begin;
  95. ui64 BeginCycles;
  96. public:
  97. TTimeLogger(const TString& message, bool verbose = true);
  98. ~TTimeLogger();
  99. void SetOK();
  100. double ElapsedTime() const;
  101. };