-
Notifications
You must be signed in to change notification settings - Fork 2
/
stopwatch.h
73 lines (61 loc) · 1.29 KB
/
stopwatch.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
#ifndef STOPWATCH_H
#define STOPWATCH_H
#include <chrono>
#include <atomic>
#include "tostring.h"
class Stopwatch
{
public:
Stopwatch();
void start();
void update();
int64_t elapsedMilliseconds();
int64_t elapsedMicroseconds();
private:
std::chrono::high_resolution_clock::time_point st, en;
};
template<typename T>
class PerSec
{
public:
typedef decltype(0 + std::declval<T>()) DiffType;
typedef std::chrono::high_resolution_clock Clock;
typedef Clock::time_point Time;
PerSec()
: lastValue(0)
, lastTime(Clock::now())
, value(0)
{
}
T signal()
{
return ++value;
}
T operator++()
{
return signal();
}
T sample()
{
auto now = Clock::now();
auto us = std::chrono::duration_cast<std::chrono::microseconds>(now - lastTime).count();
auto v = 0+value;
if (us > 0)
{
auto diff = v - lastValue;
lastValue = v;
lastTime = now;
auto persec = int64_t(diff) * 1000000 / us;
return persec;
}
return 0;
}
std::string operator()()
{
return ToString(value, " ", sample(), "/sec");
}
DiffType lastValue;
Time lastTime;
std::atomic<T> value;
};
#endif // STOPWATCH_H