thread_timer.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #ifndef BENCHMARK_THREAD_TIMER_H
  2. #define BENCHMARK_THREAD_TIMER_H
  3. #include "check.h"
  4. #include "timers.h"
  5. namespace benchmark {
  6. namespace internal {
  7. class ThreadTimer {
  8. public:
  9. ThreadTimer() = default;
  10. // Called by each thread
  11. void StartTimer() {
  12. running_ = true;
  13. start_real_time_ = ChronoClockNow();
  14. start_cpu_time_ = ThreadCPUUsage();
  15. }
  16. // Called by each thread
  17. void StopTimer() {
  18. CHECK(running_);
  19. running_ = false;
  20. real_time_used_ += ChronoClockNow() - start_real_time_;
  21. // Floating point error can result in the subtraction producing a negative
  22. // time. Guard against that.
  23. cpu_time_used_ += std::max<double>(ThreadCPUUsage() - start_cpu_time_, 0);
  24. }
  25. // Called by each thread
  26. void SetIterationTime(double seconds) { manual_time_used_ += seconds; }
  27. bool running() const { return running_; }
  28. // REQUIRES: timer is not running
  29. double real_time_used() {
  30. CHECK(!running_);
  31. return real_time_used_;
  32. }
  33. // REQUIRES: timer is not running
  34. double cpu_time_used() {
  35. CHECK(!running_);
  36. return cpu_time_used_;
  37. }
  38. // REQUIRES: timer is not running
  39. double manual_time_used() {
  40. CHECK(!running_);
  41. return manual_time_used_;
  42. }
  43. private:
  44. bool running_ = false; // Is the timer running
  45. double start_real_time_ = 0; // If running_
  46. double start_cpu_time_ = 0; // If running_
  47. // Accumulated time so far (does not contain current slice if running_)
  48. double real_time_used_ = 0;
  49. double cpu_time_used_ = 0;
  50. // Manually set iteration time. User sets this with SetIterationTime(seconds).
  51. double manual_time_used_ = 0;
  52. };
  53. } // namespace internal
  54. } // namespace benchmark
  55. #endif // BENCHMARK_THREAD_TIMER_H