//! What a runner measures about itself (spec §11.1, docs/jetstream.md §6): //! free disk, load and the kernel each claim, cheaply; and its speed, from //! a short fixed benchmark run at start and again while idle. use crate::home::Home; use flow_core::api::Facts; use std::time::Instant; /// The benchmark's time on the reference machine (Earth), in ms: a runner /// that takes as long scores 100. const REFERENCE_MS: f64 = 225.0; /// The cheap facts, with the last speed measured. pub fn now(home: &Home, speed: Option) -> Facts { Facts { free_disk_mib: free_disk_mib(&home.root), load_x100: load_x100(), speed, speed_class: speed.map(Facts::class_of), kernel: std::fs::read_to_string("/proc/sys/kernel/osrelease").ok().map(|s| s.trim().to_string()), } } /// Free space for an unprivileged writer on the file system holding `path`, in MiB. pub fn free_disk_mib(path: &std::path::Path) -> Option { use std::os::unix::ffi::OsStrExt; let c = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?; let mut s: libc::statvfs = unsafe { std::mem::zeroed() }; // SAFETY: `c` is a valid NUL-terminated path and `s` a writable statvfs. if unsafe { libc::statvfs(c.as_ptr(), &mut s) } != 0 { return None; } Some((s.f_bavail as u64).saturating_mul(s.f_frsize as u64) >> 20) } /// The 1-minute load average from /proc/loadavg, times 100. pub fn load_x100() -> Option { let text = std::fs::read_to_string("/proc/loadavg").ok()?; let first: f64 = text.split_whitespace().next()?.parse().ok()?; Some((first * 100.0).round() as u32) } /// The benchmark, one thread: BLAKE3 over 256 MiB (spec §11.1), and a sort /// of 4 Mi pseudo-random words for the integer and memory side. Answers /// the score, 100 on the reference machine, and the time it took. pub fn bench() -> (u32, u128) { let start = Instant::now(); let buf: Vec = (0..32u32 << 20).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect(); let mut h = blake3::Hasher::new(); for _ in 0..8 { h.update(&buf); } std::hint::black_box(h.finalize()); drop(buf); let mut x: u64 = 0x9e37_79b9_7f4a_7c15; let mut words: Vec = (0..4u64 << 20) .map(|_| { x ^= x << 13; x ^= x >> 7; x ^= x << 17; x }) .collect(); words.sort_unstable(); std::hint::black_box(&words); let ms = start.elapsed().as_millis().max(1); ((REFERENCE_MS * 100.0 / ms as f64).round() as u32, ms) } #[cfg(test)] mod tests { use super::*; #[test] fn the_cheap_facts_are_read_and_classes_double() { assert!(free_disk_mib(std::path::Path::new("/")).is_some()); assert!(load_x100().is_some()); assert_eq!(Facts::class_of(100), 3, "the reference machine"); assert_eq!((Facts::class_of(50), Facts::class_of(200), Facts::class_of(500), Facts::class_of(10)), (2, 4, 5, 1)); } }