stopwatch.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
  2. // Distributed under the MIT License (http://opensource.org/licenses/MIT)
  3. #pragma once
  4. #include <chrono>
  5. #include <spdlog/fmt/fmt.h>
  6. // Stopwatch support for spdlog (using std::chrono::steady_clock).
  7. // Displays elapsed seconds since construction as double.
  8. //
  9. // Usage:
  10. //
  11. // spdlog::stopwatch sw;
  12. // ...
  13. // spdlog::debug("Elapsed: {} seconds", sw); => "Elapsed 0.005116733 seconds"
  14. // spdlog::info("Elapsed: {:.6} seconds", sw); => "Elapsed 0.005163 seconds"
  15. //
  16. //
  17. // If other units are needed (e.g. millis instead of double), include "fmt/chrono.h" and use
  18. // "duration_cast<..>(sw.elapsed())":
  19. //
  20. // #include <spdlog/fmt/chrono.h>
  21. //..
  22. // using std::chrono::duration_cast;
  23. // using std::chrono::milliseconds;
  24. // spdlog::info("Elapsed {}", duration_cast<milliseconds>(sw.elapsed())); => "Elapsed 5ms"
  25. namespace spdlog {
  26. class stopwatch {
  27. using clock = std::chrono::steady_clock;
  28. std::chrono::time_point<clock> start_tp_;
  29. public:
  30. stopwatch()
  31. : start_tp_{clock::now()} {}
  32. std::chrono::duration<double> elapsed() const {
  33. return std::chrono::duration<double>(clock::now() - start_tp_);
  34. }
  35. std::chrono::milliseconds elapsed_ms() const {
  36. return std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start_tp_);
  37. }
  38. void reset() { start_tp_ = clock::now(); }
  39. };
  40. } // namespace spdlog
  41. // Support for fmt formatting (e.g. "{:012.9}" or just "{}")
  42. namespace
  43. #ifdef SPDLOG_USE_STD_FORMAT
  44. std
  45. #else
  46. fmt
  47. #endif
  48. {
  49. template <>
  50. struct formatter<spdlog::stopwatch> : formatter<double> {
  51. template <typename FormatContext>
  52. auto format(const spdlog::stopwatch &sw, FormatContext &ctx) const -> decltype(ctx.out()) {
  53. return formatter<double>::format(sw.elapsed().count(), ctx);
  54. }
  55. };
  56. } // namespace std