summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorClement Tsang <34804052+ClementTsang@users.noreply.github.com>2023-04-15 02:01:25 -0400
committerGitHub <noreply@github.com>2023-04-15 02:01:25 -0400
commit513024aefd46ad69f3a6d3cb839ad583f25da361 (patch)
tree2e1b72b9d0f41e35de15ee3c78222a0084a8a1ee
parent20902e87b97091bf7d524cdec42a87bd8e145d74 (diff)
refactor: clean up data init sleep duration code (#1101)
* refactor: clean up data init sleep duration code * const
-rw-r--r--src/app/data_harvester.rs38
1 files changed, 25 insertions, 13 deletions
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<T>(key: &str, data: &[u8]) -> Result<T, std::io::Error>