-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththrottle.h
More file actions
92 lines (68 loc) · 1.67 KB
/
throttle.h
File metadata and controls
92 lines (68 loc) · 1.67 KB
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
/**
* COPYRIGHT 2014 (C) Jason Volk
* COPYRIGHT 2014 (C) Svetlana Tkachenko
*
* DISTRIBUTED UNDER THE GNU GENERAL PUBLIC LICENSE (GPL) (see: LICENSE)
*/
class Throttle
{
time_point state;
milliseconds inc;
public:
auto &get_inc() const { return inc; }
void set_inc(const milliseconds &inc) { this->inc = inc; }
void clear() { inc = 0ms; }
milliseconds calc_rel() const;
time_point calc_abs() const;
milliseconds next();
time_point next_abs();
Throttle(const milliseconds &inc = 0ms);
Throttle(const uint64_t &inc): Throttle(milliseconds(inc)) {}
};
inline
Throttle::Throttle(const milliseconds &inc):
state(steady_clock::time_point::min()),
inc(inc)
{
}
inline
milliseconds Throttle::next()
{
using namespace std::chrono;
const auto now(steady_clock::now());
if(state < now)
{
state = now + inc;
return 0ms;
}
const auto ret(duration_cast<milliseconds>(state.time_since_epoch()) -
duration_cast<milliseconds>(now.time_since_epoch()));
state += inc;
return ret;
}
inline
time_point Throttle::next_abs()
{
const auto now(steady_clock::now());
const auto ret(state < now? now : state);
state = ret + inc;
return ret;
}
inline
milliseconds Throttle::calc_rel()
const
{
using namespace std::chrono;
const auto now(steady_clock::now());
if(state < now)
return 0ms;
return duration_cast<milliseconds>(state.time_since_epoch()) -
duration_cast<milliseconds>(now.time_since_epoch());
}
inline
time_point Throttle::calc_abs()
const
{
const auto now(steady_clock::now());
return state < now? now : state + inc;
}