Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions toolbox/sys/Time.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,27 @@ struct TypeTraits<WallTime> {
}
};

/// Throttles the invocation of a callable to not exceed a specified rate.
/// The rate is controlled by a cooldown interval.
class ThrottledInvoker {
public:
explicit ThrottledInvoker(Seconds cooldown_interval)
: cooldown_interval_(cooldown_interval) {}

template <typename Callable>
void operator()(MonoTime now, Callable&& callable)
{
if (duration_cast<Seconds>(now - last_time_invoked_) >= cooldown_interval_) {
last_time_invoked_ = now;
std::forward<Callable>(callable)();
}
}

private:
const Seconds cooldown_interval_{};
MonoTime last_time_invoked_{};
};

} // namespace util
} // namespace toolbox

Expand Down
32 changes: 32 additions & 0 deletions toolbox/sys/Time.ut.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -124,4 +124,36 @@ BOOST_AUTO_TEST_CASE(PutTimeOutput2)
BOOST_CHECK_EQUAL(stream.str(), "20180824T05:32:29.001001001");
}

BOOST_AUTO_TEST_CASE(ThrottledInvokerCheck)
{
constexpr auto threshold = 1s;
ThrottledInvoker throttler{threshold};

std::size_t count = 0;
auto fn = [&]() { ++count; };
auto now = MonoClock::now();

// First time, so throttler will invoke the callable.
// After this, the throttler should throttle until now + threshold.
throttler(now, fn);
BOOST_CHECK_EQUAL(count, 1);

now += Millis{500};
throttler(now, fn);
BOOST_CHECK_EQUAL(count, 1);

now += Millis{500};
throttler(now, fn);
BOOST_CHECK_EQUAL(count, 2);

now += Millis{500};
throttler(now, fn);
BOOST_CHECK_EQUAL(count, 2);

now += Millis{500};
throttler(now, fn);
BOOST_CHECK_EQUAL(count, 3);
}


BOOST_AUTO_TEST_SUITE_END()