//! Per-compilation worker counters, sampled only when requested. use serde::Serialize; #[derive(Clone, Copy, Serialize)] pub(super) struct ThreadUsage { cpu_ms: f64, voluntary_switches: u64, involuntary_switches: u64, block_inputs: u64, block_outputs: u64, } impl ThreadUsage { #[cfg(target_os = "linux")] pub(super) fn current() -> Option { let mut usage = std::mem::MaybeUninit::::uninit(); // A successful RUSAGE_THREAD call initializes the provided struct. if unsafe { libc::getrusage(libc::RUSAGE_THREAD, usage.as_mut_ptr()) } != 0 { return None; } let usage = unsafe { usage.assume_init() }; let millis = |time: libc::timeval| time.tv_sec as f64 * 1000.0 + time.tv_usec as f64 / 1000.0; Some(Self { cpu_ms: millis(usage.ru_utime) + millis(usage.ru_stime), voluntary_switches: usage.ru_nvcsw as u64, involuntary_switches: usage.ru_nivcsw as u64, block_inputs: usage.ru_inblock as u64, block_outputs: usage.ru_oublock as u64, }) } #[cfg(not(target_os = "linux"))] pub(super) fn current() -> Option { None } pub(super) fn between(start: Option, end: Option) -> Option { let start = start?; let end = end?; Some(Self { cpu_ms: end.cpu_ms - start.cpu_ms, voluntary_switches: end.voluntary_switches.checked_sub(start.voluntary_switches)?, involuntary_switches: end.involuntary_switches.checked_sub(start.involuntary_switches)?, block_inputs: end.block_inputs.checked_sub(start.block_inputs)?, block_outputs: end.block_outputs.checked_sub(start.block_outputs)?, }) } }