1#[derive(Debug, Clone, Copy, PartialEq, Default)]
23pub struct CpuReading {
24 pub mean: f64,
25 pub max_core: f64,
26 pub top_core: usize,
27 pub p25: f64,
29 pub p50: f64,
30 pub p75: f64,
31 pub cores: usize,
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct CpuTicks {
45 pub busy: u64,
46 pub total: u64,
47}
48
49pub fn parse_proc_stat(text: &str) -> Option<(CpuTicks, Vec<CpuTicks>)> {
51 let mut aggregate: Option<CpuTicks> = None;
52 let mut cores: Vec<(usize, CpuTicks)> = Vec::new();
53 for line in text.lines() {
54 let mut t = line.split_whitespace();
55 let Some(name) = t.next() else { continue };
56 if !name.starts_with("cpu") {
57 continue;
58 }
59 let fields: Vec<u64> = t.filter_map(|f| f.parse().ok()).collect();
60 if fields.len() < 8 {
61 continue;
62 }
63 let total: u64 = fields[..8].iter().sum();
64 let idle = fields[3] + fields[4];
65 let ticks = CpuTicks {
66 busy: total - idle,
67 total,
68 };
69 if name == "cpu" {
70 aggregate = Some(ticks);
71 } else if let Ok(n) = name[3..].parse::<usize>() {
72 cores.push((n, ticks));
73 }
74 }
75 cores.sort_by_key(|(n, _)| *n);
76 aggregate.map(|a| (a, cores.into_iter().map(|(_, t)| t).collect()))
77}
78
79pub fn cpu_util(prev: CpuTicks, cur: CpuTicks) -> f64 {
81 let dt = cur.total.saturating_sub(prev.total);
82 if dt == 0 {
83 return 0.0;
84 }
85 (cur.busy.saturating_sub(prev.busy) as f64 / dt as f64).clamp(0.0, 1.0)
86}
87
88pub fn max_core_util(prev: &[CpuTicks], cur: &[CpuTicks]) -> Option<(usize, f64)> {
91 prev.iter()
92 .zip(cur.iter())
93 .enumerate()
94 .map(|(i, (p, c))| (i, cpu_util(*p, *c)))
95 .max_by(|a, b| a.1.total_cmp(&b.1))
96}
97
98pub fn core_util_quartiles(prev: &[CpuTicks], cur: &[CpuTicks]) -> Option<(f64, f64, f64, usize)> {
110 let mut utils: Vec<f64> = prev
111 .iter()
112 .zip(cur.iter())
113 .map(|(p, c)| cpu_util(*p, *c))
114 .collect();
115 if utils.is_empty() {
116 return None;
117 }
118 utils.sort_by(f64::total_cmp);
119 let n = utils.len();
120 let at = |q: f64| -> f64 {
121 let rank = (q * n as f64).ceil().max(1.0) as usize;
123 utils[rank.min(n) - 1]
124 };
125 Some((at(0.25), at(0.50), at(0.75), n))
126}
127
128pub fn read_proc_stat() -> Option<(CpuTicks, Vec<CpuTicks>)> {
131 std::fs::read_to_string("/proc/stat")
132 .ok()
133 .and_then(|t| parse_proc_stat(&t))
134}
135
136#[cfg(test)]
137mod tests {
138 use super::*;
139
140 #[test]
143 fn one_hot_core_shows_in_max_not_mean() {
144 let stat_t0 = "\
145cpu 1000 0 0 8000 0 0 0 0 0 0
146cpu0 1000 0 0 0 0 0 0 0 0 0
147cpu1 0 0 0 4000 0 0 0 0 0 0
148cpu2 0 0 0 4000 0 0 0 0 0 0";
149 let stat_t1 = "\
150cpu 2000 0 0 16000 0 0 0 0 0 0
151cpu0 2000 0 0 0 0 0 0 0 0 0
152cpu1 0 0 0 8000 0 0 0 0 0 0
153cpu2 0 0 0 8000 0 0 0 0 0 0";
154 let (a0, c0) = parse_proc_stat(stat_t0).unwrap();
155 let (a1, c1) = parse_proc_stat(stat_t1).unwrap();
156 let mean = cpu_util(a0, a1);
157 let (core, max) = max_core_util(&c0, &c1).unwrap();
158 assert!((mean - 1000.0 / 9000.0).abs() < 1e-9, "mean {mean}");
159 assert_eq!(core, 0);
160 assert!((max - 1.0).abs() < 1e-9, "core0 fully busy, got {max}");
161
162 let (p25, p50, p75, cores) = core_util_quartiles(&c0, &c1).unwrap();
166 assert_eq!(cores, 3);
167 assert!((p25 - 0.0).abs() < 1e-9, "p25 {p25}");
168 assert!((p50 - 0.0).abs() < 1e-9, "median core is IDLE, got {p50}");
169 assert!((p75 - 1.0).abs() < 1e-9, "p75 {p75}");
170 }
171
172 #[test]
176 fn quartiles_separate_broad_saturation_from_one_hot_core() {
177 let stat_t0 = "\
178cpu 0 0 0 12000 0 0 0 0 0 0
179cpu0 0 0 0 4000 0 0 0 0 0 0
180cpu1 0 0 0 4000 0 0 0 0 0 0
181cpu2 0 0 0 4000 0 0 0 0 0 0";
182 let stat_t1 = "\
183cpu 12000 0 0 12000 0 0 0 0 0 0
184cpu0 4000 0 0 4000 0 0 0 0 0 0
185cpu1 4000 0 0 4000 0 0 0 0 0 0
186cpu2 4000 0 0 4000 0 0 0 0 0 0";
187 let (_, c0) = parse_proc_stat(stat_t0).unwrap();
188 let (_, c1) = parse_proc_stat(stat_t1).unwrap();
189 let (_, max) = max_core_util(&c0, &c1).unwrap();
190 let (p25, p50, p75, cores) = core_util_quartiles(&c0, &c1).unwrap();
191 assert_eq!(cores, 3);
192 assert!((max - 1.0).abs() < 1e-9, "max {max}");
195 assert!((p25 - 1.0).abs() < 1e-9, "p25 {p25}");
198 assert!((p50 - 1.0).abs() < 1e-9, "p50 {p50}");
199 assert!((p75 - 1.0).abs() < 1e-9, "p75 {p75}");
200 }
201
202 #[test]
205 fn quartiles_are_nearest_rank_over_real_cores() {
206 let single = vec![CpuTicks {
207 busy: 0,
208 total: 1000,
209 }];
210 let single_end = vec![CpuTicks {
211 busy: 250,
212 total: 2000,
213 }];
214 let (p25, p50, p75, cores) = core_util_quartiles(&single, &single_end).unwrap();
215 assert_eq!(cores, 1);
216 assert!((p25 - 0.25).abs() < 1e-9);
218 assert!((p50 - 0.25).abs() < 1e-9);
219 assert!((p75 - 0.25).abs() < 1e-9);
220 assert!(core_util_quartiles(&[], &[]).is_none());
222 }
223
224 #[test]
227 fn iowait_does_not_count_as_busy() {
228 let t0 = parse_proc_stat("cpu 0 0 0 0 0 0 0 0 0 0").unwrap().0;
229 let t1 = parse_proc_stat("cpu 0 0 0 500 500 0 0 0 0 0").unwrap().0;
230 assert_eq!(cpu_util(t0, t1), 0.0);
231 }
232}