perf_step_timer.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. #pragma once
  7. #include "monitoring/perf_level_imp.h"
  8. #include "monitoring/statistics_impl.h"
  9. #include "rocksdb/system_clock.h"
  10. namespace ROCKSDB_NAMESPACE {
  11. class PerfStepTimer {
  12. public:
  13. explicit PerfStepTimer(
  14. uint64_t* metric, SystemClock* clock = nullptr, bool use_cpu_time = false,
  15. PerfLevel enable_level = PerfLevel::kEnableTimeExceptForMutex,
  16. Statistics* statistics = nullptr, uint32_t ticker_type = 0)
  17. : perf_counter_enabled_(perf_level >= enable_level),
  18. use_cpu_time_(use_cpu_time),
  19. ticker_type_(ticker_type),
  20. clock_((perf_counter_enabled_ || statistics != nullptr)
  21. ? (clock ? clock : SystemClock::Default().get())
  22. : nullptr),
  23. start_(0),
  24. metric_(metric),
  25. statistics_(statistics) {}
  26. ~PerfStepTimer() { Stop(); }
  27. void Start() {
  28. if (perf_counter_enabled_ || statistics_ != nullptr) {
  29. start_ = time_now();
  30. }
  31. }
  32. void Measure() {
  33. if (start_) {
  34. uint64_t now = time_now();
  35. *metric_ += now - start_;
  36. start_ = now;
  37. }
  38. }
  39. void Stop() {
  40. if (start_) {
  41. uint64_t duration = time_now() - start_;
  42. if (perf_counter_enabled_) {
  43. *metric_ += duration;
  44. }
  45. if (statistics_ != nullptr) {
  46. RecordTick(statistics_, ticker_type_, duration);
  47. }
  48. start_ = 0;
  49. }
  50. }
  51. private:
  52. uint64_t time_now() {
  53. if (!use_cpu_time_) {
  54. return clock_->NowNanos();
  55. } else {
  56. return clock_->CPUNanos();
  57. }
  58. }
  59. const bool perf_counter_enabled_;
  60. const bool use_cpu_time_;
  61. uint32_t ticker_type_;
  62. SystemClock* const clock_;
  63. uint64_t start_;
  64. uint64_t* metric_;
  65. Statistics* statistics_;
  66. };
  67. } // namespace ROCKSDB_NAMESPACE