-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.h
112 lines (96 loc) · 1.97 KB
/
timer.h
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
#pragma once
// C
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <stdlib.h>
// C++
#include <iostream>
#include <vector>
/// --- B E G I N T I M E R --- ///
template <typename T>
T ClockToSeconds(clock_t c) {
return (T(c) / CLOCKS_PER_SEC);
}
template <typename TimeType>
class Timer {
private:
clock_t _t1;
clock_t _t2;
TimeType m_time_sec;
TimeType mTotalTime;
bool m_bDidCalcTime;
public:
Timer() {
_t1 = clock();
_t2 = clock();
m_bDidCalcTime = false;
m_time_sec = TimeType(0.0);
mTotalTime = TimeType(0.0);
}
typedef enum {
TIME_UNKNOWN,
TIME_START,
TIME_STOP
} When;
void start() {
_t1 = clock();
setDidCalcTime(false);
}
TimeType stop() {
_t2 = clock();
setDidCalcTime(false);
return getTime();
}
TimeType getTime() {
if (!didCalcTime()) {
calcTime();
updateTotalTime();
}
return m_time_sec;
}
inline TimeType getTotalTime() const {
return mTotalTime;
}
inline bool didCalcTime() const { return m_bDidCalcTime; }
inline clock_t getClockDiff() {
return getClock(TIME_STOP) - getClock(TIME_START);
}
clock_t getClock(When w = TIME_UNKNOWN) {
switch (w) {
case TIME_START: return _t1;
case TIME_STOP: return _t2;
default: return clock();
}
}
private:
inline void updateTotalTime() {
mTotalTime += m_time_sec;
}
void calcTime() {
setTime(ClockToSeconds<TimeType>(getClockDiff()));
setDidCalcTime(true);
}
void setDidCalcTime(bool bDidCalc) {
m_bDidCalcTime = bDidCalc;
}
void setTime(TimeType t) {
m_time_sec = t;
}
};
#define TIME(func) \
([&]() -> float { \
Timer<float> timer; \
timer.start(); \
func; \
timer.stop(); \
return timer.getTime(); \
})();
#define TIME_ASSIGN(assign, func) \
([&]() -> float { \
Timer<float> timer; \
timer.start(); \
assign = func; \
timer.stop(); \
return timer.getTime(); \
})();