-
Notifications
You must be signed in to change notification settings - Fork 7
/
simple-timer.hpp
124 lines (99 loc) · 2.67 KB
/
simple-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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/*
* simpler-timer.hpp
*
* A simple timer class that allows timing of scoped regions.
*/
#ifndef SIMPLE_TIMER_HPP_
#define SIMPLE_TIMER_HPP_
#include <cinttypes>
#include <stdexcept>
#include <chrono>
#include <string>
#include <cstdio>
#if !defined(ENABLE_TIMER) || !ENABLE_TIMER
#define DISABLE_TIMER
#endif
template <typename CLOCK>
class SimpleTimerT {
using nanos_type = std::int64_t;
public:
enum State {
STARTED, STOPPED
};
SimpleTimerT(bool createStarted = true) : elapsed_(0), mode_(STOPPED) {
if (createStarted) start();
}
void checkState(State expected, const char *msg) {
if (mode_ != expected) {
if (mode_ != STARTED && mode_ != STOPPED) {
throw std::logic_error("bad state (maybe uninit?)");
} else {
throw std::logic_error(msg);
}
}
}
void start() {
checkState(STOPPED, "counter already started");
last_stamp_ = nanos();
mode_ = STARTED;
}
void stop() {
checkState(STARTED, "counter already stopped");
elapsed_ += nanos() - last_stamp_;
mode_ = STOPPED;
}
bool isStarted() {
return mode_ == STARTED;
}
nanos_type elapsedNanos() {
return elapsed_ + (isStarted() ? nanos() - last_stamp_ : 0);
}
template <typename DURATION>
DURATION elapsedDuration() {
return std::chrono::duration_cast<DURATION>(std::chrono::nanoseconds(elapsedNanos()));
}
template <typename DURATION>
typename DURATION::rep elapsed() {
return elapsedDuration<DURATION>().count();
}
private:
nanos_type elapsed_, last_stamp_;
State mode_;
static nanos_type nanos() {
return std::chrono::duration_cast<std::chrono::nanoseconds>(CLOCK::now().time_since_epoch()).count();
}
};
using SimpleTimer = SimpleTimerT<std::chrono::high_resolution_clock>;
class LoggingTimer : public SimpleTimer {
public:
const static int DEFAULT_WIDTH = 0;
LoggingTimer(std::string message, int width = DEFAULT_WIDTH)
#ifndef DISABLE_TIMER
:
message_{std::move(message)},
nameWidth(width),
printed_(false)
#endif
{}
void printElapsed() {
#ifndef DISABLE_TIMER
double ms = elapsedNanos() / 1000000.0;
std::fprintf(stderr, "%-*s: %7.4f ms\n", nameWidth, message_.c_str(), ms);
printed_ = true;
#endif
}
~LoggingTimer() {
#ifndef DISABLE_TIMER
if (!printed_) {
printElapsed();
}
#endif
}
private:
#ifndef DISABLE_TIMER
std::string message_;
int nameWidth;
bool printed_;
#endif
};
#endif /* SIMPLE_TIMER_HPP_ */