Skip to main content

oa/core/
perf_stat.rs

1//! Rolling-window performance statistics accumulator.
2//!
3//! Port provenance: `oa/core/perfStat.h`.
4//!
5//! Accumulates a configurable sliding window of `f64` samples and computes
6//! mean, stddev, min, max, and percentiles. A warmup period discards the first
7//! N samples (GPU boost-clock / JIT cache warm-up effects).
8//!
9//! # Usage
10//!
11//! ```rust,ignore
12//! let mut stat = oa::PerfStat::new("step_ms", 200, 20);
13//! stat.push(gpu_ms);
14//! if stat.is_ready() {
15//!     println!("mean={:.3}ms p95={:.3}ms", stat.mean(), stat.p95());
16//! }
17//! ```
18
19/// Rolling-window performance statistics.
20///
21/// No GPU dependency; pure CPU value struct.
22pub struct PerfStat {
23	name: String,
24	window: usize,
25	warmup: usize,
26	total_count: u64,
27	ring: Vec<f64>,
28	head: usize,
29	filled: usize,
30	sum: f64,
31	sum_sq: f64,
32	last_val: f64,
33}
34
35impl PerfStat {
36	/// Create a new accumulator.
37	///
38	/// - `name`   — human-readable label used in diagnostics.
39	/// - `window` — rolling window capacity (clamped to 1).
40	/// - `warmup` — samples discarded before statistics are valid.
41	pub fn new(name: &str, window: usize, warmup: usize) -> Self {
42		let window = window.max(1);
43		Self {
44			name: name.to_owned(),
45			window,
46			warmup,
47			total_count: 0,
48			ring: vec![0.0; window],
49			head: 0,
50			filled: 0,
51			sum: 0.0,
52			sum_sq: 0.0,
53			last_val: 0.0,
54		}
55	}
56
57	/// Push one sample.
58	pub fn push(&mut self, value: f64) {
59		self.last_val = value;
60		self.total_count += 1;
61
62		if self.total_count <= self.warmup as u64 {
63			return; // discard warmup samples
64		}
65
66		let slot = self.head % self.window;
67		// Evict old sample if the window is full.
68		if self.filled == self.window {
69			let old = self.ring[slot];
70			self.sum -= old;
71			self.sum_sq -= old * old;
72		} else {
73			self.filled += 1;
74		}
75
76		self.ring[slot] = value;
77		self.sum += value;
78		self.sum_sq += value * value;
79		self.head = slot + 1;
80	}
81
82	/// True when warmup is done and at least one window sample is available.
83	pub fn is_ready(&self) -> bool {
84		self.filled > 0
85	}
86
87	/// Mean of the current window. Valid only when `is_ready()`.
88	pub fn mean(&self) -> f64 {
89		if self.filled == 0 {
90			return 0.0;
91		}
92		self.sum / self.filled as f64
93	}
94
95	/// Population standard deviation of the current window.
96	pub fn stddev(&self) -> f64 {
97		if self.filled < 2 {
98			return 0.0;
99		}
100		let n = self.filled as f64;
101		let var = (self.sum_sq / n) - (self.sum / n).powi(2);
102		var.max(0.0).sqrt()
103	}
104
105	/// Minimum value in the current window.
106	pub fn min(&self) -> f64 {
107		self
108			.window_slice()
109			.iter()
110			.cloned()
111			.fold(f64::INFINITY, f64::min)
112	}
113
114	/// Maximum value in the current window.
115	pub fn max(&self) -> f64 {
116		self
117			.window_slice()
118			.iter()
119			.cloned()
120			.fold(f64::NEG_INFINITY, f64::max)
121	}
122
123	/// 50th percentile (median) of the current window.
124	pub fn p50(&self) -> f64 {
125		self.percentile(0.50)
126	}
127
128	/// 95th percentile of the current window.
129	pub fn p95(&self) -> f64 {
130		self.percentile(0.95)
131	}
132
133	/// 99th percentile of the current window.
134	pub fn p99(&self) -> f64 {
135		self.percentile(0.99)
136	}
137
138	/// Last pushed value regardless of warmup.
139	pub fn last(&self) -> f64 {
140		self.last_val
141	}
142
143	/// Total samples pushed (including warmup).
144	pub fn count(&self) -> u64 {
145		self.total_count
146	}
147
148	/// Human-readable name supplied at construction.
149	pub fn name(&self) -> &str {
150		&self.name
151	}
152
153	/// Reset all state to initial.
154	pub fn reset(&mut self) {
155		self.total_count = 0;
156		self.filled = 0;
157		self.head = 0;
158		self.sum = 0.0;
159		self.sum_sq = 0.0;
160		self.last_val = 0.0;
161		self.ring.fill(0.0);
162	}
163
164	// ─── helpers ─────────────────────────────────────────────────────────
165
166	/// Return the live window samples in push order.
167	fn window_slice(&self) -> Vec<f64> {
168		if self.filled == 0 {
169			return Vec::new();
170		}
171		let mut out = Vec::with_capacity(self.filled);
172		// Oldest sample is at (head % window) when window is full; at 0 when not.
173		let start = if self.filled == self.window {
174			self.head % self.window
175		} else {
176			0
177		};
178		for i in 0..self.filled {
179			out.push(self.ring[(start + i) % self.window]);
180		}
181		out
182	}
183
184	fn percentile(&self, p: f64) -> f64 {
185		if self.filled == 0 {
186			return 0.0;
187		}
188		let mut sorted = self.window_slice();
189		sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
190		let idx = ((p * (sorted.len() - 1) as f64).round() as usize).min(sorted.len() - 1);
191		sorted[idx]
192	}
193}