stopwatch.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 <spdlog/fmt/fmt.h>
  5. #include <chrono>
  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 "duration_cast<..>(sw.elapsed())":
  18. //
  19. // #include <spdlog/fmt/chrono.h>
  20. //..
  21. // using std::chrono::duration_cast;
  22. // using std::chrono::milliseconds;
  23. // spdlog::info("Elapsed {}", duration_cast<milliseconds>(sw.elapsed())); => "Elapsed 5ms"
  24. namespace spdlog {
  25. class stopwatch
  26. {
  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. {}
  33. std::chrono::duration<double> elapsed() const
  34. {
  35. return std::chrono::duration<double>(clock::now() - start_tp_);
  36. }
  37. void reset()
  38. {
  39. start_tp_ = clock::now();
  40. }
  41. };
  42. } // namespace spdlog
  43. // Support for fmt formatting (e.g. "{:012.9}" or just "{}")
  44. namespace
  45. #ifdef SPDLOG_USE_STD_FORMAT
  46. std
  47. #else
  48. fmt
  49. #endif
  50. {
  51. template<>
  52. struct formatter<spdlog::stopwatch> : formatter<double>
  53. {
  54. template<typename FormatContext>
  55. auto format(const spdlog::stopwatch &sw, FormatContext &ctx) const -> decltype(ctx.out())
  56. {
  57. return formatter<double>::format(sw.elapsed().count(), ctx);
  58. }
  59. };
  60. } // namespace std