Add simple polled rate limiter

This commit is contained in:
Danny Robson 2013-08-08 10:48:44 +10:00
parent 3615bb2fa1
commit 03eab1354a
2 changed files with 31 additions and 0 deletions

View File

@ -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): util::polled_duration::polled_duration (std::string name, uint64_t interval):
m_name (name), m_name (name),

View File

@ -43,6 +43,18 @@ namespace util {
} time; } time;
}; };
// ------------------------------------------------------------------------
class rate_limiter {
public:
rate_limiter (unsigned rate);
void poll (void);
protected:
uint64_t m_last;
unsigned m_target;
};
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
class polled_duration { class polled_duration {
public: public: