From 0b5ce4e0c55691a9341832b21f98a45d2ac75acd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Wo=CC=81jcik?= <3044353+pwojcikdev@users.noreply.github.com> Date: Mon, 12 Feb 2024 16:42:07 +0100 Subject: [PATCH] `nano::elapse ()` helper --- nano/lib/stats.cpp | 8 ++------ nano/lib/utility.hpp | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/nano/lib/stats.cpp b/nano/lib/stats.cpp index 025d6cf207..44844228da 100644 --- a/nano/lib/stats.cpp +++ b/nano/lib/stats.cpp @@ -281,8 +281,6 @@ void nano::stats::run_one (std::unique_lock & lock) debug_assert (!mutex.try_lock ()); debug_assert (lock.owns_lock ()); - auto now = std::chrono::steady_clock::now (); // Only sample clock if necessary as this impacts node performance due to frequent usage - // TODO: Replace with a proper std::chrono time std::time_t time = std::chrono::system_clock::to_time_t (std::chrono::system_clock::now ()); tm local_tm = *localtime (&time); @@ -290,20 +288,18 @@ void nano::stats::run_one (std::unique_lock & lock) // Counters if (config.log_counters_interval.count () > 0) { - if (nano::elapsed (log_last_count_writeout, config.log_counters_interval)) + if (nano::elapse (log_last_count_writeout, config.log_counters_interval)) { log_counters_impl (log_count, local_tm); - log_last_count_writeout = now; } } // Samples if (config.log_samples_interval.count () > 0) { - if (nano::elapsed (log_last_sample_writeout, config.log_samples_interval)) + if (nano::elapse (log_last_sample_writeout, config.log_samples_interval)) { log_samples_impl (log_sample, local_tm); - log_last_sample_writeout = now; } } } diff --git a/nano/lib/utility.hpp b/nano/lib/utility.hpp index 06646e95c1..321cfccdb5 100644 --- a/nano/lib/utility.hpp +++ b/nano/lib/utility.hpp @@ -192,7 +192,16 @@ constexpr TARGET_TYPE narrow_cast (SOURCE_TYPE const & val) // Issue #3748 void sort_options_description (const boost::program_options::options_description & source, boost::program_options::options_description & target); +} +/* + * Clock utilities + */ +namespace nano +{ +/** + * Steady clock should always be used for measuring time intervals + */ using clock = std::chrono::steady_clock; /** @@ -214,6 +223,22 @@ bool elapsed (nano::clock::time_point const & last, Duration const & duration) { return elapsed (last, duration, nano::clock::now ()); } + +/** + * Check whether time elapsed since `last` is greater than `duration` and update `last` if true + * Force usage of steady clock + */ +template +bool elapse (nano::clock::time_point & last, Duration const & duration) +{ + auto now = nano::clock::now (); + if (last + duration < now) + { + last = now; + return true; + } + return false; +} } namespace nano::util