From 513024aefd46ad69f3a6d3cb839ad583f25da361 Mon Sep 17 00:00:00 2001 From: Clement Tsang <34804052+ClementTsang@users.noreply.github.com> Date: Sat, 15 Apr 2023 02:01:25 -0400 Subject: refactor: clean up data init sleep duration code (#1101) * refactor: clean up data init sleep duration code * const --- src/app/data_harvester.rs | 38 +++++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/app/data_harvester.rs b/src/app/data_harvester.rs index 362b7251..2f4633bf 100644 --- a/src/app/data_harvester.rs +++ b/src/app/data_harvester.rs @@ -194,20 +194,10 @@ impl DataCollector { self.update_data(); - // Sleep a few seconds to avoid potentially weird data... - let sleep_duration = { - cfg_if::cfg_if! { - if #[cfg(target_os = "freebsd")] { - // FreeBSD's min duration value is 1s, which is a bit too long for me so I'll accept the one-time - // inaccuracy. - std::time::Duration::from_millis(250) - } else { - sysinfo::System::MINIMUM_CPU_UPDATE_INTERVAL + Duration::from_millis(1) - } - } - }; + // Sleep a few seconds to avoid potentially weird data. + const SLEEP: Duration = get_sleep_duration(); - std::thread::sleep(sleep_duration); + std::thread::sleep(SLEEP); self.data.cleanup(); } @@ -497,6 +487,28 @@ impl DataCollector { } } +/// We set a sleep duration between 10ms and 250ms, ideally sysinfo's [`System::MINIMUM_CPU_UPDATE_INTERVAL`] + 1. +/// +/// We bound the upper end to avoid waiting too long (e.g. FreeBSD is 1s, which I'm fine with losing +/// accuracy on for the first refresh), and we bound the lower end just to avoid the off-chance that +/// refreshing too quickly causes problems. This second case should only happen on unsupported +/// systems via sysinfo, in which case [`System::MINIMUM_CPU_UPDATE_INTERVAL`] is defined as 0. +/// +/// We also do `INTERVAL + 1` for some wiggle room, just in case. +const fn get_sleep_duration() -> Duration { + const MIN_SLEEP: u64 = 10; + const MAX_SLEEP: u64 = 250; + const INTERVAL: u64 = System::MINIMUM_CPU_UPDATE_INTERVAL.as_millis() as u64; + + if INTERVAL < MIN_SLEEP { + Duration::from_millis(MIN_SLEEP) + } else if INTERVAL > MAX_SLEEP { + Duration::from_millis(MAX_SLEEP) + } else { + Duration::from_millis(INTERVAL + 1) + } +} + #[cfg(target_os = "freebsd")] /// Deserialize [libxo](https://www.freebsd.org/cgi/man.cgi?query=libxo&apropos=0&sektion=0&manpath=FreeBSD+13.1-RELEASE+and+Ports&arch=default&format=html) JSON data fn deserialize_xo(key: &str, data: &[u8]) -> Result -- cgit v1.2.3