//! CPU and memory of this process from `/proc/self`, by thread name, with //! the spike's own counters, sampled once a second on a thread of their own. //! //! CPU is in percent of one core (200 = two cores busy). Threads are grouped //! by name without a trailing number (`llvmpipe-12` → `llvmpipe`), so the //! software renderer's share (Mesa's `llvmpipe-*` threads, which a GPU would //! replace) is told apart from the decoder, the converter and GPUI's main //! thread. use std::collections::BTreeMap; use std::fs; use std::io::Write; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{Duration, Instant}; use serde_json::{Value, json}; /// A number the spike counts up (frames shown) or sets (images alive); the /// meter reports counters per second and gauges as they are. #[derive(Clone, Default)] pub struct Counter(Arc); impl Counter { /// Add one. pub fn incr(&self) { self.0.fetch_add(1, Ordering::Relaxed); } /// Add `n`. pub fn add(&self, n: u64) { self.0.fetch_add(n, Ordering::Relaxed); } /// Set (gauges). pub fn set(&self, value: u64) { self.0.store(value, Ordering::Relaxed); } /// The current value. pub fn get(&self) -> u64 { self.0.load(Ordering::Relaxed) } } /// CPU ticks of the process and of each thread group, and the resident /// memory, at one moment. #[derive(Clone, Debug)] pub struct Snapshot { at: Instant, process: u64, threads: BTreeMap, rss: u64, } /// `utime + stime` and the name of a `/proc/.../stat` line. fn ticks_of(stat: &str) -> Option<(String, u64)> { let open = stat.find('(')?; let close = stat.rfind(')')?; let name = stat.get(open + 1..close)?.to_owned(); let fields: Vec<&str> = stat.get(close + 1..)?.split_whitespace().collect(); // Fields 14 and 15 of proc(5); the remainder starts at field 3. let utime: u64 = fields.get(11)?.parse().ok()?; let stime: u64 = fields.get(12)?.parse().ok()?; Some((name, utime + stime)) } /// A thread's group: its name without a trailing number or separator. pub fn group_of(name: &str) -> String { let trimmed = name.trim_end_matches(|c: char| c.is_ascii_digit()); let trimmed = trimmed.trim_end_matches(['-', '_', ':', ' ', '#']); if trimmed.is_empty() { name.to_owned() } else { trimmed.to_owned() } } impl Snapshot { /// Read `/proc/self` now. pub fn now() -> Self { Self::of("self") } /// Read `/proc/` now (`"self"` or a process id). pub fn of(process: &str) -> Self { let proc = format!("/proc/{process}"); let process = fs::read_to_string(format!("{proc}/stat")) .ok() .and_then(|s| ticks_of(&s)) .map_or(0, |(_, t)| t); let mut threads = BTreeMap::new(); if let Ok(dir) = fs::read_dir(format!("{proc}/task")) { for entry in dir.flatten() { let Ok(stat) = fs::read_to_string(entry.path().join("stat")) else { continue }; if let Some((name, ticks)) = ticks_of(&stat) { *threads.entry(group_of(&name)).or_insert(0) += ticks; } } } let rss = fs::read_to_string(format!("{proc}/statm")) .ok() .and_then(|s| s.split_whitespace().nth(1)?.parse::().ok()) .map_or(0, |pages| pages * rustix::param::page_size() as u64); Self { at: Instant::now(), process, threads, rss } } /// Resident memory in MiB. pub fn rss_mib(&self) -> f64 { self.rss as f64 / (1024.0 * 1024.0) } } /// CPU in percent of one core between two snapshots: the process's and each /// thread group's (groups that exited in between count from zero). pub fn cpu_between(a: &Snapshot, b: &Snapshot) -> (f64, BTreeMap) { let hz = rustix::param::clock_ticks_per_second() as f64; let secs = b.at.duration_since(a.at).as_secs_f64().max(1e-6); let pct = |ticks: u64| ticks as f64 / hz / secs * 100.0; let process = pct(b.process.saturating_sub(a.process)); let threads = b .threads .iter() .map(|(name, &t)| (name.clone(), pct(t.saturating_sub(*a.threads.get(name).unwrap_or(&0))))) .filter(|(_, p)| *p > 0.0) .collect(); (process, threads) } /// What a run measures and how long. pub struct Meter { /// The run's settings, copied into every line. pub config: Value, /// Counted up; reported per second. pub counters: Vec<(&'static str, Counter)>, /// Set; reported as they are. pub gauges: Vec<(&'static str, Counter)>, /// Seconds not averaged at the start (start-up, the first keyframe). pub warmup: Duration, /// The whole run, warm-up included; the process exits after it. pub duration: Duration, /// JSON lines: one per second, then the summary (`"summary": true`). pub out: Option, } impl Meter { /// Sample once a second on a thread; after `duration` write the summary /// and end the process with `exit_code`. pub fn start(self, exit_code: Arc) { std::thread::Builder::new() .name("spike-meter".into()) .spawn(move || self.run(&exit_code)) .expect("a meter thread"); } fn run(self, exit_code: &AtomicU64) { let mut out = self.out.as_ref().map(|p| fs::File::create(p).expect("the meter's file")); let mut emit = |line: &Value| { let text = line.to_string(); println!("{text}"); if let Some(f) = out.as_mut() { let _ = writeln!(f, "{text}"); } }; let start = Instant::now(); let values = |list: &[(&'static str, Counter)]| -> Vec { list.iter().map(|(_, c)| c.get()).collect() }; let mut last = Snapshot::now(); let mut last_counts = values(&self.counters); let mut steady: Option<(Snapshot, Vec)> = None; let mut cpu_samples: Vec = Vec::new(); let mut rss_max = last.rss_mib(); let rss_start = last.rss_mib(); let mut rss_steady_start = None; loop { std::thread::sleep(Duration::from_secs(1)); let now = Snapshot::now(); let counts = values(&self.counters); let (cpu, threads) = cpu_between(&last, &now); let secs = now.at.duration_since(last.at).as_secs_f64(); let rates: serde_json::Map = self .counters .iter() .zip(counts.iter().zip(&last_counts)) .map(|((name, _), (c, l))| { ((*name).to_owned(), json!(round((c - l) as f64 / secs))) }) .collect(); let gauges: serde_json::Map = self.gauges.iter().map(|(n, g)| ((*n).to_owned(), json!(g.get()))).collect(); let elapsed = start.elapsed(); emit(&json!({ "t": round(elapsed.as_secs_f64()), "cpu": round(cpu), "threads": threads.iter().map(|(k, v)| (k.clone(), json!(round(*v)))).collect::>(), "rss_mib": round(now.rss_mib()), "rates": rates, "gauges": gauges, })); rss_max = rss_max.max(now.rss_mib()); if elapsed >= self.warmup { if steady.is_none() { steady = Some((now.clone(), counts.clone())); rss_steady_start = Some(now.rss_mib()); } else { cpu_samples.push(cpu); } } if elapsed >= self.duration { let (first, first_counts) = steady.unwrap_or_else(|| (last.clone(), last_counts.clone())); let (cpu, threads) = cpu_between(&first, &now); let secs = now.at.duration_since(first.at).as_secs_f64().max(1e-6); let rates: serde_json::Map = self .counters .iter() .zip(counts.iter().zip(&first_counts)) .map(|((name, _), (c, f))| { ((*name).to_owned(), json!(round((c - f) as f64 / secs))) }) .collect(); cpu_samples.sort_by(f64::total_cmp); let pick = |q: f64| { cpu_samples .get(((cpu_samples.len() as f64 - 1.0) * q).round() as usize) .copied() .unwrap_or(cpu) }; emit(&json!({ "summary": true, "config": self.config, "steady_seconds": round(secs), "cpu_mean": round(cpu), "cpu_p10": round(pick(0.1)), "cpu_p90": round(pick(0.9)), "threads_mean": threads.iter().map(|(k, v)| (k.clone(), json!(round(*v)))).collect::>(), "rates_mean": rates, "gauges_end": gauges, "rss_mib_start": round(rss_start), "rss_mib_steady_start": rss_steady_start.map(round), "rss_mib_end": round(now.rss_mib()), "rss_mib_max": round(rss_max), "rss_growth_mib_per_min": rss_steady_start.map(|s| round((now.rss_mib() - s) / secs * 60.0)), })); std::process::exit(exit_code.load(Ordering::Relaxed) as i32); } last = now; last_counts = counts; } } } fn round(v: f64) -> f64 { (v * 10.0).round() / 10.0 } #[cfg(test)] mod tests { use super::*; #[test] fn groups_drop_trailing_numbers() { assert_eq!(group_of("llvmpipe-12"), "llvmpipe"); assert_eq!(group_of("tokio-runtime-w"), "tokio-runtime-w"); assert_eq!(group_of("spike-video"), "spike-video"); assert_eq!(group_of("1234"), "1234"); } #[test] fn stat_lines_parse_with_spaces_in_names() { let line = "42 (a b) c) S 1 2 3 4 5 6 7 8 9 10 100 23 0 0 20 0 1 0 0"; assert_eq!(ticks_of(line), Some(("a b) c".to_owned(), 123))); } }