From 7fc18e145f40a88d4579e370881721aa2ecd9485 Mon Sep 17 00:00:00 2001 From: Danny Robson Date: Wed, 30 Mar 2022 13:29:33 +1000 Subject: [PATCH] time: add wait/reset to period_limiter --- time.cpp | 16 +++++++++++++++- time.hpp | 9 +++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/time.cpp b/time.cpp index a14e4fa4..a13b8963 100644 --- a/time.cpp +++ b/time.cpp @@ -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)), diff --git a/time.hpp b/time.hpp index 56e2d1d2..e1858b11 100644 --- a/time.hpp +++ b/time.hpp @@ -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;