/
timer.hpp
64 lines (52 loc) · 1.43 KB
/
timer.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#pragma once
#include <string>
#include <chrono>
#include <json.hpp>
/// A simple stack-based library used to time nested parts of a program.
namespace otto::util::timer {
using timer_id = std::string;
using time_point = std::chrono::time_point<
std::chrono::steady_clock, std::chrono::nanoseconds>;
using time_duration = time_point::duration::rep;
#if OTTO_ENABLE_TIMERS
struct TimerData {
timer_id id;
time_duration duration;
std::vector<TimerData> children;
nlohmann::json to_json() const
{
auto obj = nlohmann::json::object();
obj["id"] = id;
obj["duration"] = duration;
if (!this->children.empty()) {
auto children = nlohmann::json::array();
for (auto const& timer_data : this->children) {
children.push_back(timer_data.to_json());
}
obj["children"] = children;
}
return obj;
}
};
struct [[nodiscard]] ScopedTimer {
ScopedTimer(timer_id id);
~ScopedTimer();
private:
timer_id id;
time_point start;
std::vector<TimerData> children;
ScopedTimer *parent;
};
/// Start a timer with id `id`, and push it to the stack.
ScopedTimer start(timer_id id);
void save_data();
#else
void start(timer_id id);
void save_data();
#endif
} // otto::util::timer
#if OTTO_ENABLE_TIMERS
#define TIME_SCOPE(id) auto scoped_timer = ::otto::util::timer::start(id)
#else
#define TIME_SCOPE(id)
#endif