perf_step_timer.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 "rocksdb/env.h"
  9. #include "util/stop_watch.h"
  10. namespace ROCKSDB_NAMESPACE {
  11. class PerfStepTimer {
  12. public:
  13. explicit PerfStepTimer(
  14. uint64_t* metric, Env* env = 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. env_((perf_counter_enabled_ || statistics != nullptr)
  20. ? ((env != nullptr) ? env : Env::Default())
  21. : nullptr),
  22. start_(0),
  23. metric_(metric),
  24. statistics_(statistics),
  25. ticker_type_(ticker_type) {}
  26. ~PerfStepTimer() {
  27. Stop();
  28. }
  29. void Start() {
  30. if (perf_counter_enabled_ || statistics_ != nullptr) {
  31. start_ = time_now();
  32. }
  33. }
  34. uint64_t time_now() {
  35. if (!use_cpu_time_) {
  36. return env_->NowNanos();
  37. } else {
  38. return env_->NowCPUNanos();
  39. }
  40. }
  41. void Measure() {
  42. if (start_) {
  43. uint64_t now = time_now();
  44. *metric_ += now - start_;
  45. start_ = now;
  46. }
  47. }
  48. void Stop() {
  49. if (start_) {
  50. uint64_t duration = time_now() - start_;
  51. if (perf_counter_enabled_) {
  52. *metric_ += duration;
  53. }
  54. if (statistics_ != nullptr) {
  55. RecordTick(statistics_, ticker_type_, duration);
  56. }
  57. start_ = 0;
  58. }
  59. }
  60. private:
  61. const bool perf_counter_enabled_;
  62. const bool use_cpu_time_;
  63. Env* const env_;
  64. uint64_t start_;
  65. uint64_t* metric_;
  66. Statistics* statistics_;
  67. uint32_t ticker_type_;
  68. };
  69. } // namespace ROCKSDB_NAMESPACE