-
Notifications
You must be signed in to change notification settings - Fork 63
/
simple-timer.hpp
81 lines (62 loc) · 1.82 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
/*
* 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>
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>;
#endif /* SIMPLE_TIMER_HPP_ */