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