-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.hh
executable file
·69 lines (65 loc) · 2.1 KB
/
timer.hh
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
#include <chrono>
#include <functional>
#include <iostream>
class ScopedTimer {
private:
//////////////////////
// Type definitions //
//////////////////////
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::time_point<Clock> Time;
#ifdef TIMER_USES_MICROSECONDS
typedef std::chrono::microseconds TimeUnit;
#else
typedef std::chrono::milliseconds TimeUnit;
#endif
public:
typedef std::function<void(long long duration)> CallBack;
private:
/**
* @brief A function object that is called with the lifetime on destruction.
*
* The function takes as argument a value of type long long with the lifetime.
* The units of that time depends on the chosen resolution of the timer.
*
* If no callback is provided, a default callback that does nothing is used by
* default.
*/
CallBack onDestructionCall_;
/// Construction time of the object
Time construction_;
public:
/// Constructor
ScopedTimer(CallBack onDestructionCall = [](long long duration)->void {})
: onDestructionCall_(onDestructionCall)
, construction_(Clock::now()) {
/*
Note: Do not put anything here as it will count on the time the object
is measuring. If you really need to do that then move the
initialization of the construction_ attribute to be the last thing the
constructor does.
*/
}
// copy constructor
ScopedTimer(const ScopedTimer& st)
: onDestructionCall_(st.onDestructionCall_)
, construction_(st.construction_) {}
/// Returns the elapsed time since the construction of the object
long long elapsed(void) const {
auto now = Clock::now();
return std::chrono::duration_cast<TimeUnit>(now - construction_).count();
}
/// Destructor
~ScopedTimer(void) { onDestructionCall_(elapsed()); }
};
inline std::ostream& operator<<(std::ostream& os, const ScopedTimer& timer) {
os << timer.elapsed();
#ifdef TIMER_USES_MICROSECONDS
os << " us.";
#else
os << " ms.";
#endif
return os;
}
#define COUT_TIMER(name, str) \
ScopedTimer name([](long long d) {std::cout << str << (d / 1000.0) << std::endl;})