time: add wait/reset to period_limiter

This commit is contained in:
Danny Robson 2022-03-30 13:29:33 +10:00
parent c50e24e3be
commit 7fc18e145f
2 changed files with 24 additions and 1 deletions

View File

@ -106,18 +106,32 @@ cruft::period_limiter::period_limiter (u64 _period)
//-----------------------------------------------------------------------------
void cruft::period_limiter::poll (void)
void
cruft::period_limiter::wait (void) const
{
auto const now = nanoseconds ();
auto const diff = now - m_prev;
if (diff < m_period)
sleep (m_period - diff);
}
//-----------------------------------------------------------------------------
void cruft::period_limiter::reset (void)
{
m_prev = nanoseconds ();
}
//-----------------------------------------------------------------------------
void cruft::period_limiter::poll (void)
{
wait ();
reset ();
}
///////////////////////////////////////////////////////////////////////////////
cruft::polled_duration::polled_duration (std::string name, uint64_t interval):
m_name (std::move (name)),

View File

@ -77,12 +77,21 @@ namespace cruft {
///////////////////////////////////////////////////////////////////////////
/// Ensured to ensure a minimum period has elapsed since a previous
/// invocation.
class period_limiter {
public:
explicit period_limiter (std::chrono::nanoseconds _period);
explicit period_limiter (u64);
/// Wait until the period has elapsed and reset the last activation
/// time.
void poll (void);
/// Wait until the period has elapsed. Does not reset the last
/// activation time.
void wait (void) const;
/// Reset the last activated time. Does not block.
void reset (void);
private:
u64 m_period;