#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct CpuReading {
pub mean: f64,
pub max_core: f64,
pub top_core: usize,
pub p25: f64,
pub p50: f64,
pub p75: f64,
pub cores: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CpuTicks {
pub busy: u64,
pub total: u64,
}
pub fn parse_proc_stat(text: &str) -> Option<(CpuTicks, Vec<CpuTicks>)> {
let mut aggregate: Option<CpuTicks> = None;
let mut cores: Vec<(usize, CpuTicks)> = Vec::new();
for line in text.lines() {
let mut t = line.split_whitespace();
let Some(name) = t.next() else { continue };
if !name.starts_with("cpu") {
continue;
}
let fields: Vec<u64> = t.filter_map(|f| f.parse().ok()).collect();
if fields.len() < 8 {
continue;
}
let total: u64 = fields[..8].iter().sum();
let idle = fields[3] + fields[4];
let ticks = CpuTicks {
busy: total - idle,
total,
};
if name == "cpu" {
aggregate = Some(ticks);
} else if let Ok(n) = name[3..].parse::<usize>() {
cores.push((n, ticks));
}
}
cores.sort_by_key(|(n, _)| *n);
aggregate.map(|a| (a, cores.into_iter().map(|(_, t)| t).collect()))
}
pub fn cpu_util(prev: CpuTicks, cur: CpuTicks) -> f64 {
let dt = cur.total.saturating_sub(prev.total);
if dt == 0 {
return 0.0;
}
(cur.busy.saturating_sub(prev.busy) as f64 / dt as f64).clamp(0.0, 1.0)
}
pub fn max_core_util(prev: &[CpuTicks], cur: &[CpuTicks]) -> Option<(usize, f64)> {
prev.iter()
.zip(cur.iter())
.enumerate()
.map(|(i, (p, c))| (i, cpu_util(*p, *c)))
.max_by(|a, b| a.1.total_cmp(&b.1))
}
pub fn core_util_quartiles(prev: &[CpuTicks], cur: &[CpuTicks]) -> Option<(f64, f64, f64, usize)> {
let mut utils: Vec<f64> = prev
.iter()
.zip(cur.iter())
.map(|(p, c)| cpu_util(*p, *c))
.collect();
if utils.is_empty() {
return None;
}
utils.sort_by(f64::total_cmp);
let n = utils.len();
let at = |q: f64| -> f64 {
let rank = (q * n as f64).ceil().max(1.0) as usize;
utils[rank.min(n) - 1]
};
Some((at(0.25), at(0.50), at(0.75), n))
}
pub fn read_proc_stat() -> Option<(CpuTicks, Vec<CpuTicks>)> {
std::fs::read_to_string("/proc/stat")
.ok()
.and_then(|t| parse_proc_stat(&t))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_hot_core_shows_in_max_not_mean() {
let stat_t0 = "\
cpu 1000 0 0 8000 0 0 0 0 0 0
cpu0 1000 0 0 0 0 0 0 0 0 0
cpu1 0 0 0 4000 0 0 0 0 0 0
cpu2 0 0 0 4000 0 0 0 0 0 0";
let stat_t1 = "\
cpu 2000 0 0 16000 0 0 0 0 0 0
cpu0 2000 0 0 0 0 0 0 0 0 0
cpu1 0 0 0 8000 0 0 0 0 0 0
cpu2 0 0 0 8000 0 0 0 0 0 0";
let (a0, c0) = parse_proc_stat(stat_t0).unwrap();
let (a1, c1) = parse_proc_stat(stat_t1).unwrap();
let mean = cpu_util(a0, a1);
let (core, max) = max_core_util(&c0, &c1).unwrap();
assert!((mean - 1000.0 / 9000.0).abs() < 1e-9, "mean {mean}");
assert_eq!(core, 0);
assert!((max - 1.0).abs() < 1e-9, "core0 fully busy, got {max}");
let (p25, p50, p75, cores) = core_util_quartiles(&c0, &c1).unwrap();
assert_eq!(cores, 3);
assert!((p25 - 0.0).abs() < 1e-9, "p25 {p25}");
assert!((p50 - 0.0).abs() < 1e-9, "median core is IDLE, got {p50}");
assert!((p75 - 1.0).abs() < 1e-9, "p75 {p75}");
}
#[test]
fn quartiles_separate_broad_saturation_from_one_hot_core() {
let stat_t0 = "\
cpu 0 0 0 12000 0 0 0 0 0 0
cpu0 0 0 0 4000 0 0 0 0 0 0
cpu1 0 0 0 4000 0 0 0 0 0 0
cpu2 0 0 0 4000 0 0 0 0 0 0";
let stat_t1 = "\
cpu 12000 0 0 12000 0 0 0 0 0 0
cpu0 4000 0 0 4000 0 0 0 0 0 0
cpu1 4000 0 0 4000 0 0 0 0 0 0
cpu2 4000 0 0 4000 0 0 0 0 0 0";
let (_, c0) = parse_proc_stat(stat_t0).unwrap();
let (_, c1) = parse_proc_stat(stat_t1).unwrap();
let (_, max) = max_core_util(&c0, &c1).unwrap();
let (p25, p50, p75, cores) = core_util_quartiles(&c0, &c1).unwrap();
assert_eq!(cores, 3);
assert!((max - 1.0).abs() < 1e-9, "max {max}");
assert!((p25 - 1.0).abs() < 1e-9, "p25 {p25}");
assert!((p50 - 1.0).abs() < 1e-9, "p50 {p50}");
assert!((p75 - 1.0).abs() < 1e-9, "p75 {p75}");
}
#[test]
fn quartiles_are_nearest_rank_over_real_cores() {
let single = vec![CpuTicks {
busy: 0,
total: 1000,
}];
let single_end = vec![CpuTicks {
busy: 250,
total: 2000,
}];
let (p25, p50, p75, cores) = core_util_quartiles(&single, &single_end).unwrap();
assert_eq!(cores, 1);
assert!((p25 - 0.25).abs() < 1e-9);
assert!((p50 - 0.25).abs() < 1e-9);
assert!((p75 - 0.25).abs() < 1e-9);
assert!(core_util_quartiles(&[], &[]).is_none());
}
#[test]
fn iowait_does_not_count_as_busy() {
let t0 = parse_proc_stat("cpu 0 0 0 0 0 0 0 0 0 0").unwrap().0;
let t1 = parse_proc_stat("cpu 0 0 0 500 500 0 0 0 0 0").unwrap().0;
assert_eq!(cpu_util(t0, t1), 0.0);
}
}