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