Add simple polled rate limiter
This commit is contained in:
parent
3615bb2fa1
commit
03eab1354a
19
time.cpp
19
time.cpp
@ -93,6 +93,25 @@ delta_clock::seconds (void) {
|
||||
}
|
||||
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
util::rate_limiter::rate_limiter (unsigned rate):
|
||||
m_last (nanoseconds ()),
|
||||
m_target (static_cast<double> (SECOND) / rate)
|
||||
{ ; }
|
||||
|
||||
|
||||
void
|
||||
util::rate_limiter::poll (void) {
|
||||
uint64_t now = nanoseconds ();
|
||||
uint64_t total = now - m_last;
|
||||
|
||||
if (total < m_target)
|
||||
sleep (m_target - total);
|
||||
|
||||
m_last = now;
|
||||
}
|
||||
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
util::polled_duration::polled_duration (std::string name, uint64_t interval):
|
||||
m_name (name),
|
||||
|
12
time.hpp
12
time.hpp
@ -43,6 +43,18 @@ namespace util {
|
||||
} time;
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
class rate_limiter {
|
||||
public:
|
||||
rate_limiter (unsigned rate);
|
||||
|
||||
void poll (void);
|
||||
|
||||
protected:
|
||||
uint64_t m_last;
|
||||
unsigned m_target;
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
class polled_duration {
|
||||
public:
|
||||
|
Loading…
Reference in New Issue
Block a user