forked from Expensify/Bedrock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WallClockTimer.h
48 lines (40 loc) · 1.79 KB
/
WallClockTimer.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
#pragma once
// A WallClockTimer is a class that can be used by multiple threads to count wall clock time that some task is
// occurring. This won't double-count the same wall clock time for two different threads that are working in parallel.
class WallClockTimer {
public:
// Create a new WallClockTimer.
WallClockTimer();
// Start counting time. Has no effect if another thread is already counting time.
void start();
// Stop counting time. Has no effect if another thread is still counting time.
void stop();
// Return to time periods, the first being total wall clock time elapsed, and the second being the time that the
// timer was actually running. Resets both these values upon call.
// That is to say, if you call 'getStatsAndReset' every 10s, you should see pairs where the first value is always
// approximately 10s, and the second value is always in the range 0-10s.
pair<chrono::milliseconds, chrono::milliseconds> getStatsAndReset();
private:
mutex _m;
uint64_t _count;
chrono::steady_clock::time_point _currentStart;
chrono::steady_clock::time_point _absoluteStart;
chrono::milliseconds _elapsedRecorded;
};
// You can use an AutoScopedWallClockTimer to start timing with a WallClockTimer and have timing stop automatically
// when the AutoScopedWallClockTimer goes out of scope. This allows you not not worry about doing `timer.stop()` in
// multiple return statement locations in a function or to worry about what happens if an exception is thrown while
// your timer is running.
class AutoScopedWallClockTimer {
public:
AutoScopedWallClockTimer(WallClockTimer& timer) :
_timer(timer)
{
_timer.start();
}
~AutoScopedWallClockTimer() {
_timer.stop();
}
private:
WallClockTimer& _timer;
};