AutoTimer.h 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. /*
  2. * Copyright 2015-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #pragma once
  17. #include <chrono>
  18. #include <string>
  19. #include <type_traits>
  20. #include <folly/Conv.h>
  21. #include <folly/Format.h>
  22. #include <folly/Optional.h>
  23. #include <folly/String.h>
  24. #include <glog/logging.h>
  25. namespace folly {
  26. // Default logger
  27. enum class GoogleLoggerStyle { SECONDS, PRETTY };
  28. template <GoogleLoggerStyle>
  29. struct GoogleLogger;
  30. /**
  31. * Automatically times a block of code, printing a specified log message on
  32. * destruction or whenever the log() method is called. For example:
  33. *
  34. * AutoTimer t("Foo() completed");
  35. * doWork();
  36. * t.log("Do work finished");
  37. * doMoreWork();
  38. *
  39. * This would print something like:
  40. * "Do work finished in 1.2 seconds"
  41. * "Foo() completed in 4.3 seconds"
  42. *
  43. * You can customize what you use as the logger and clock. The logger needs
  44. * to have an operator()(StringPiece, std::chrono::duration<double>) that
  45. * gets a message and a duration. The clock needs to model Clock from
  46. * std::chrono.
  47. *
  48. * The default logger logs usings glog. It only logs if the message is
  49. * non-empty, so you can also just use this class for timing, e.g.:
  50. *
  51. * AutoTimer t;
  52. * doWork()
  53. * const auto how_long = t.log();
  54. */
  55. template <
  56. class Logger = GoogleLogger<GoogleLoggerStyle::PRETTY>,
  57. class Clock = std::chrono::high_resolution_clock>
  58. class AutoTimer final {
  59. public:
  60. using DoubleSeconds = std::chrono::duration<double>;
  61. explicit AutoTimer(
  62. std::string&& msg = "",
  63. const DoubleSeconds& minTimetoLog = DoubleSeconds::zero(),
  64. Logger&& logger = Logger())
  65. : destructionMessage_(std::move(msg)),
  66. minTimeToLog_(minTimetoLog),
  67. logger_(std::move(logger)) {}
  68. // It doesn't really make sense to copy AutoTimer
  69. // Movable to make sure the helper method for creating an AutoTimer works.
  70. AutoTimer(const AutoTimer&) = delete;
  71. AutoTimer(AutoTimer&&) = default;
  72. AutoTimer& operator=(const AutoTimer&) = delete;
  73. AutoTimer& operator=(AutoTimer&&) = default;
  74. ~AutoTimer() {
  75. if (destructionMessage_) {
  76. log(destructionMessage_.value());
  77. }
  78. }
  79. DoubleSeconds log(StringPiece msg = "") {
  80. return logImpl(Clock::now(), msg);
  81. }
  82. template <typename... Args>
  83. DoubleSeconds log(Args&&... args) {
  84. auto now = Clock::now();
  85. return logImpl(now, to<std::string>(std::forward<Args>(args)...));
  86. }
  87. template <typename... Args>
  88. DoubleSeconds logFormat(Args&&... args) {
  89. auto now = Clock::now();
  90. return logImpl(now, format(std::forward<Args>(args)...).str());
  91. }
  92. private:
  93. // We take in the current time so that we don't measure time to call
  94. // to<std::string> or format() in the duration.
  95. DoubleSeconds logImpl(std::chrono::time_point<Clock> now, StringPiece msg) {
  96. auto duration = now - start_;
  97. if (duration >= minTimeToLog_) {
  98. logger_(msg, duration);
  99. }
  100. start_ = Clock::now(); // Don't measure logging time
  101. return duration;
  102. }
  103. Optional<std::string> destructionMessage_;
  104. std::chrono::time_point<Clock> start_ = Clock::now();
  105. DoubleSeconds minTimeToLog_;
  106. Logger logger_;
  107. };
  108. template <
  109. class Logger = GoogleLogger<GoogleLoggerStyle::PRETTY>,
  110. class Clock = std::chrono::high_resolution_clock>
  111. auto makeAutoTimer(
  112. std::string&& msg = "",
  113. const std::chrono::duration<double>& minTimeToLog =
  114. std::chrono::duration<double>::zero(),
  115. Logger&& logger = Logger()) {
  116. return AutoTimer<Logger, Clock>(
  117. std::move(msg), minTimeToLog, std::move(logger));
  118. }
  119. template <GoogleLoggerStyle Style>
  120. struct GoogleLogger final {
  121. void operator()(StringPiece msg, const std::chrono::duration<double>& sec)
  122. const {
  123. if (msg.empty()) {
  124. return;
  125. }
  126. if (Style == GoogleLoggerStyle::PRETTY) {
  127. LOG(INFO) << msg << " in "
  128. << prettyPrint(sec.count(), PrettyType::PRETTY_TIME);
  129. } else {
  130. LOG(INFO) << msg << " in " << sec.count() << " seconds";
  131. }
  132. }
  133. };
  134. } // namespace folly