time: add a period_limiter class

This commit is contained in:
Danny Robson 2022-03-22 13:18:01 +10:00
parent bfc5069e23
commit c50e24e3be
2 changed files with 44 additions and 2 deletions

View File

@ -14,6 +14,7 @@
using cruft::delta_clock; using cruft::delta_clock;
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
static const uint64_t SECOND = 1'000'000'000UL; static const uint64_t SECOND = 1'000'000'000UL;
static const uint64_t MILLISECOND = 1'000'000UL; static const uint64_t MILLISECOND = 1'000'000UL;
@ -91,6 +92,32 @@ cruft::rate_limiter::poll (void)
} }
///////////////////////////////////////////////////////////////////////////////
cruft::period_limiter::period_limiter (std::chrono::nanoseconds _period)
: period_limiter (_period.count ())
{ ; }
//-----------------------------------------------------------------------------
cruft::period_limiter::period_limiter (u64 _period)
: m_period (_period)
, m_prev (nanoseconds () - _period)
{ ; }
//-----------------------------------------------------------------------------
void cruft::period_limiter::poll (void)
{
auto const now = nanoseconds ();
auto const diff = now - m_prev;
if (diff < m_period)
sleep (m_period - diff);
m_prev = nanoseconds ();
}
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
cruft::polled_duration::polled_duration (std::string name, uint64_t interval): cruft::polled_duration::polled_duration (std::string name, uint64_t interval):
m_name (std::move (name)), m_name (std::move (name)),

View File

@ -3,12 +3,13 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
* *
* Copyright 2010-2016 Danny Robson <danny@nerdcruft.net> * Copyright 2010-2016, 2022 Danny Robson <danny@nerdcruft.net>
*/ */
#pragma once #pragma once
#include "stats.hpp" #include "./std.hpp"
#include "./stats.hpp"
#include <chrono> #include <chrono>
#include <cstdint> #include <cstdint>
@ -75,6 +76,20 @@ namespace cruft {
}; };
///////////////////////////////////////////////////////////////////////////
class period_limiter {
public:
explicit period_limiter (std::chrono::nanoseconds _period);
explicit period_limiter (u64);
void poll (void);
private:
u64 m_period;
u64 m_prev;
};
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
class polled_duration { class polled_duration {
public: public: