Skip to main content

uzor_framework/
profiler.rs

1//! Generic named-stage frame profiler + the shared EMA helper.
2//!
3//! Moved from `the old framework module::frame_profiler`. There is no JSON
4//! sink (design L-U7); callers read [`FrameProfiler::stage_ms`] /
5//! [`FrameProfiler::stages`].
6//!
7//! Stage names are caller-supplied `&'static str` keys, not a fixed enum.
8//! The aggregator owns no clock and no serializer: feed milliseconds in,
9//! read the smoothed map back out.
10//!
11//! **This module owns NO clock.** It lives in the platform-agnostic core
12//! (`std::time::Instant` panics at runtime on `wasm32-unknown-unknown`,
13//! and this crate compiles for every window backend), so the aggregator
14//! only ever accepts caller-measured durations via
15//! [`FrameProfiler::record_ms`] — pure math + naming. The measuring edge
16//! stays wherever a real monotonic clock exists (e.g.
17//! `uzor-desktop::Manager` brackets with `Instant` and feeds the result
18//! in; a web backend would feed `performance.now()` deltas).
19//!
20//! [`EmaF64`] deduplicates a smoothing formula that used to be
21//! hand-rolled independently in two places: the source app's own
22//! `FrameProfile::ema` (`previous * 0.92 + sample * 0.08`) and
23//! `Manager`'s own whole-frame `fps_ema` (`previous * 0.9 + sample *
24//! 0.1`). `Manager::fps_ema`'s public behavior (the `f32` field, its
25//! exact smoothing formula/seed) is unchanged — it now computes that
26//! same formula through an [`EmaF64`] tracker instead of the formula
27//! written out inline a second time.
28
29use std::collections::HashMap;
30
31/// Exponential moving average over `f64` samples, with an
32/// alpha-per-`update`-call smoothing factor (rather than a
33/// fixed-at-construction one) so a single small primitive can back both
34/// this module's per-stage profiler (alpha `0.08`, the source app's own
35/// constant) and `uzor-desktop::Manager`'s own whole-frame `fps_ema`
36/// (alpha `0.1`) without needing two copies of the formula.
37#[derive(Debug, Clone, Copy, PartialEq)]
38pub struct EmaF64 {
39    value: f64,
40    initialized: bool,
41}
42
43impl Default for EmaF64 {
44    fn default() -> Self {
45        Self {
46            value: 0.0,
47            initialized: false,
48        }
49    }
50}
51
52impl EmaF64 {
53    /// A fresh, uninitialized tracker — its very first [`EmaF64::update`]
54    /// call wins outright (no smoothing against `0.0`).
55    pub fn new() -> Self {
56        Self::default()
57    }
58
59    /// A tracker pre-seeded with `value`, marked initialized — the first
60    /// real [`EmaF64::update`] call blends against `value` instead of
61    /// replacing it outright. Useful when a caller has a sensible
62    /// starting guess (e.g. an assumed `60.0` fps before the first frame
63    /// has actually been timed) rather than wanting the very first
64    /// sample to jump straight to its own raw value.
65    pub fn seeded(value: f64) -> Self {
66        Self {
67            value,
68            initialized: true,
69        }
70    }
71
72    /// Fold `sample` into the running average at smoothing factor
73    /// `alpha` (`0.0..=1.0`; higher = more responsive to new samples,
74    /// lower = smoother/slower) and return the new value. The very first
75    /// call on an uninitialized (`Self::new`/`Self::default`) tracker
76    /// always wins outright — matches both source call sites' own
77    /// `if initialized { blend } else { sample }` cold-start rule,
78    /// avoiding a synthetic warm-up period biased toward whatever value
79    /// the struct happened to start at.
80    pub fn update(&mut self, sample: f64, alpha: f64) -> f64 {
81        self.value = if self.initialized {
82            self.value * (1.0 - alpha) + sample * alpha
83        } else {
84            sample
85        };
86        self.initialized = true;
87        self.value
88    }
89
90    /// Current smoothed value (`0.0` if never updated and not seeded).
91    pub fn value(&self) -> f64 {
92        self.value
93    }
94
95    /// Whether at least one [`EmaF64::update`] has run, or the tracker
96    /// was constructed via [`EmaF64::seeded`].
97    pub fn is_initialized(&self) -> bool {
98        self.initialized
99    }
100}
101
102/// Named-stage, per-frame profiler with independent EMA smoothing per
103/// stage — the generic mechanism behind the source app's own
104/// `FrameProfile`. Stage names are caller-supplied `&'static str` keys
105/// (e.g. `"grid"`, `"scene_build"`, `"overlay"`), not a fixed enum, so
106/// any app's own frame-phase vocabulary ports over unchanged.
107///
108/// Clock-free by design (module doc) — the caller measures each stage
109/// with whatever monotonic clock its platform has and feeds the elapsed
110/// milliseconds into [`FrameProfiler::record_ms`].
111#[derive(Debug, Clone)]
112pub struct FrameProfiler {
113    alpha: f64,
114    stages: HashMap<&'static str, EmaF64>,
115    frames: u64,
116}
117
118impl FrameProfiler {
119    /// The source app's own smoothing constant
120    /// (`previous * 0.92 + sample * 0.08`).
121    pub const DEFAULT_ALPHA: f64 = 0.08;
122
123    /// A profiler smoothing every stage at `alpha` (see [`EmaF64::update`]).
124    pub fn new(alpha: f64) -> Self {
125        Self {
126            alpha,
127            stages: HashMap::new(),
128            frames: 0,
129        }
130    }
131
132    /// Record a caller-measured sample in milliseconds for `stage`,
133    /// folding it into that stage's own running EMA — the stage's
134    /// tracker is created (uninitialized) on first use, so its own first
135    /// sample wins outright rather than blending against a synthetic
136    /// `0.0`.
137    pub fn record_ms(&mut self, stage: &'static str, sample_ms: f64) {
138        self.stages
139            .entry(stage)
140            .or_default()
141            .update(sample_ms, self.alpha);
142    }
143
144    /// Current smoothed value (ms) for `stage`, or `0.0` if it has never
145    /// been recorded.
146    pub fn stage_ms(&self, stage: &str) -> f64 {
147        self.stages.get(stage).map_or(0.0, EmaF64::value)
148    }
149
150    /// Every currently-tracked stage's smoothed value — iteration order
151    /// is NOT guaranteed (backed by a `HashMap`); a caller that needs a
152    /// fixed field order should read [`FrameProfiler::stage_ms`] per
153    /// named stage instead.
154    pub fn stages(&self) -> impl Iterator<Item = (&'static str, f64)> + '_ {
155        self.stages.iter().map(|(&name, ema)| (name, ema.value()))
156    }
157
158    /// Total frames [`FrameProfiler::end_frame`] has been called for.
159    pub fn frame_count(&self) -> u64 {
160        self.frames
161    }
162
163    /// Bump the frame counter — call once per frame (typically after
164    /// recording that frame's stages), independent of how many stages
165    /// were actually recorded that frame.
166    pub fn end_frame(&mut self) {
167        self.frames = self.frames.wrapping_add(1);
168    }
169}
170
171impl Default for FrameProfiler {
172    fn default() -> Self {
173        Self::new(Self::DEFAULT_ALPHA)
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    #[test]
182    fn ema_first_sample_wins_outright_when_uninitialized() {
183        let mut ema = EmaF64::new();
184        assert!(!ema.is_initialized());
185        assert_eq!(ema.update(42.0, 0.1), 42.0);
186        assert!(ema.is_initialized());
187    }
188
189    #[test]
190    fn ema_blends_subsequent_samples_by_alpha() {
191        let mut ema = EmaF64::new();
192        ema.update(100.0, 0.1);
193        let next = ema.update(0.0, 0.1);
194        assert!(
195            (next - 90.0).abs() < 1e-9,
196            "expected 100*0.9 + 0*0.1 = 90, got {next}"
197        );
198    }
199
200    #[test]
201    fn ema_seeded_blends_the_seed_on_the_very_first_real_sample() {
202        let mut ema = EmaF64::seeded(60.0);
203        assert!(ema.is_initialized());
204        let next = ema.update(120.0, 0.1);
205        assert!((next - (60.0 * 0.9 + 120.0 * 0.1)).abs() < 1e-9);
206    }
207
208    #[test]
209    fn ema_converges_toward_a_sustained_constant_sample() {
210        let mut ema = EmaF64::new();
211        for _ in 0..500 {
212            ema.update(16.0, 0.2);
213        }
214        assert!(
215            (ema.value() - 16.0).abs() < 1e-6,
216            "a sustained constant sample must converge, got {}",
217            ema.value()
218        );
219    }
220
221    #[test]
222    fn frame_profiler_default_alpha_matches_the_source_apps_own_smoothing_constant() {
223        assert_eq!(FrameProfiler::DEFAULT_ALPHA, 0.08);
224        let profiler = FrameProfiler::default();
225        assert_eq!(profiler.frame_count(), 0);
226    }
227
228    #[test]
229    fn frame_profiler_record_ms_creates_and_smooths_a_named_stage() {
230        let mut profiler = FrameProfiler::new(0.08);
231        profiler.record_ms("grid", 10.0);
232        assert_eq!(
233            profiler.stage_ms("grid"),
234            10.0,
235            "first sample must win outright"
236        );
237        let smoothed = {
238            profiler.record_ms("grid", 20.0);
239            profiler.stage_ms("grid")
240        };
241        assert!((smoothed - (10.0 * 0.92 + 20.0 * 0.08)).abs() < 1e-9);
242    }
243
244    #[test]
245    fn frame_profiler_stage_ms_returns_zero_for_a_never_recorded_stage() {
246        let profiler = FrameProfiler::new(0.08);
247        assert_eq!(profiler.stage_ms("never_recorded"), 0.0);
248    }
249
250    #[test]
251    fn frame_profiler_end_frame_increments_the_frame_counter_independent_of_stage_recording() {
252        let mut profiler = FrameProfiler::new(0.08);
253        profiler.end_frame();
254        profiler.record_ms("grid", 1.0);
255        profiler.end_frame();
256        assert_eq!(profiler.frame_count(), 2);
257    }
258
259    #[test]
260    fn frame_profiler_stages_iterates_every_recorded_stage() {
261        let mut profiler = FrameProfiler::new(0.08);
262        profiler.record_ms("grid", 1.0);
263        profiler.record_ms("overlay", 2.0);
264        let mut names: Vec<&str> = profiler.stages().map(|(name, _)| name).collect();
265        names.sort_unstable();
266        assert_eq!(names, vec!["grid", "overlay"]);
267    }
268}