-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathIntervalChecker.h
79 lines (57 loc) · 2.34 KB
/
IntervalChecker.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
//-----------------------------------------------------------------------------
/** @file libboardgame_base/IntervalChecker.h
@author Markus Enzenberger
@copyright GNU General Public License version 3 or later */
//-----------------------------------------------------------------------------
#ifndef LIBBOARDGAME_BASE_INTERVAL_CHECKER_H
#define LIBBOARDGAME_BASE_INTERVAL_CHECKER_H
#include <functional>
#include "TimeSource.h"
namespace libboardgame_base {
using namespace std;
//-----------------------------------------------------------------------------
/** Reduces regular calls to an expensive function to a given time interval.
The class assumes that its check() function is called in regular time
intervals and forwards only every n'th call to the expensive function with
n being adjusted dynamically to a given time interval. check() returns
true, if the expensive function was called and returned true in the
past. */
class IntervalChecker
{
public:
/** Constructor.
@param time_source The time source. The lifetime of this
parameter must exceed the lifetime of the class instance.
@param time_interval The time interval in seconds
@param f The expensive function */
IntervalChecker(TimeSource& time_source, double time_interval,
const function<bool()>& f);
bool operator()();
/** Disable the dynamic updating of the interval.
Can be used if the non-reproducability of the time measurement used
for dynamic updating of the check interval is undesirable.
@param interval The fixed interval (number of calls) to use for calling
the expensive function. (Must be greater zero). */
void set_deterministic(unsigned interval);
protected:
TimeSource& m_time_source;
private:
bool m_is_first_check = true;
bool m_is_deterministic = false;
bool m_result = false;
unsigned m_count = 1;
unsigned m_count_interval = 1;
double m_time_interval;
double m_last_time;
function<bool()> m_function;
bool check_expensive();
};
inline bool IntervalChecker::operator()()
{
if (--m_count == 0)
return check_expensive();
return m_result;
}
//-----------------------------------------------------------------------------
} // namespace libboardgame_base
#endif // LIBBOARDGAME_BASE_INTERVAL_CHECKER_H