Skip to main content

crcbl_ui/
budget.rs

1//! The budget row compares CPU active time with the measured GPU elapsed span.
2//! GPU elapsed includes scheduling gaps and contention, not just active work;
3//! the larger-span classification is a diagnostic, not a throughput guarantee.
4//!
5//! Topic 40's first debug-panel row, and the reason it is
6//! first: "'GPU-bound' is the first question and nothing answers it today". The
7//! two numbers come from opposite ends of the engine — the CPU one from the
8//! frame span `crcbl_core::trace` records, the GPU one from
9//! `crcbl_render::timing`'s per-pass timestamps — and neither of those knows
10//! about the other, so this is where they meet. It knows about neither in turn:
11//! it takes nanoseconds.
12//!
13//! # The two numbers are about different frames, and the row does not pretend
14//! otherwise
15//!
16//! The GPU report is **frames latent by design** — a ring of query sets resolved
17//! only when a slot comes back round, so the newest GPU number is about a frame a
18//! few frames ago, and topic 40 is explicit that no consumer
19//! "fixes" that by stalling. So a row pairing *this* frame's CPU cost with *this*
20//! frame's GPU cost would be stating something it cannot know.
21//!
22//! What it shows instead is two **distributions**: p50 and p95 over a rolling
23//! window of [`DEFAULT_FRAME_WINDOW`] frames each. A window that long is not
24//! moved by the two or three frames the ring lags — the samples in it are the
25//! same frames give or take the offset — while a single-frame pairing would be
26//! wrong by exactly that offset. The lag is shown rather than hidden: the row
27//! carries the frame number the newest GPU sample came from, so a reader can
28//! watch it trail the frame counter.
29//!
30//! # It reports nothing until it can report a percentile
31//!
32//! A p95 over five samples is the largest of the five, which is a maximum wearing
33//! a percentile's name. [`MIN_PERCENTILE_SAMPLES`] is the point below which that
34//! is true, so below it the row says how full the window is and nothing else.
35
36use core::fmt;
37use core::time::Duration;
38
39use crate::debug::{DEFAULT_FRAME_WINDOW, DebugModule, DebugSection};
40
41/// Samples a window needs before [`BudgetStats`] reports a percentile.
42///
43/// Re-exported rather than defined here: `crcbl bench` reports the same
44/// percentiles over its own samples, and the rank arithmetic and the count it is
45/// honest at are one piece of knowledge. [`crcbl_core::stats`] is where it
46/// lives, and where its derivation is tested across every count below it.
47pub use crcbl_core::stats::MIN_PERCENTILE_SAMPLES;
48
49/// Which of the CPU and the GPU is the frame's budget.
50#[derive(Clone, Copy, PartialEq, Eq, Debug)]
51pub enum Bound {
52    /// Neither window holds [`MIN_PERCENTILE_SAMPLES`] yet.
53    Unknown,
54    /// The CPU p50 is the larger.
55    Cpu,
56    /// The GPU p50 is the larger.
57    Gpu,
58    /// The two p50s are equal.
59    Tied,
60}
61
62impl Bound {
63    /// How the row spells it.
64    #[must_use]
65    pub const fn as_str(self) -> &'static str {
66        match self {
67            Self::Unknown => "unknown",
68            Self::Cpu => "cpu",
69            Self::Gpu => "gpu",
70            Self::Tied => "tied",
71        }
72    }
73}
74
75impl fmt::Display for Bound {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        f.write_str(self.as_str())
78    }
79}
80
81/// One rolling window of per-frame nanosecond costs.
82///
83/// The window itself is [`crcbl_core::stats::Window`], which
84/// `crcbl_render::pass_stats` also keeps one of per pass: the eviction, the
85/// sort and the count below which a p95 is the maximum are one piece of
86/// knowledge and this row is not the only reader of it.
87type Window = crcbl_core::stats::Window<DEFAULT_FRAME_WINDOW>;
88
89/// CPU active time against measured GPU elapsed time, over rolling windows.
90///
91/// Fed once a frame from both ends — [`BudgetStats::record_cpu`] with the frame
92/// span's active duration, [`BudgetStats::record_gpu`] with the outer interval
93/// the timers resolved — and read by the debug panel. See the
94/// [module docs](self) for why the two are shown as distributions rather than
95/// paired frame by frame.
96#[derive(Clone, Debug, Default)]
97pub struct BudgetStats {
98    cpu: Window,
99    gpu: Window,
100    /// Which frame the newest GPU sample was about. Also the guard against
101    /// counting one latent report several times: the ring hands the same
102    /// `FrameTimings` back until a new slot resolves.
103    gpu_frame: Option<u64>,
104}
105
106impl BudgetStats {
107    /// Empty windows.
108    #[must_use]
109    pub fn new() -> Self {
110        Self::default()
111    }
112
113    /// Records what this frame cost on the CPU.
114    pub fn record_cpu(&mut self, cpu: Duration) {
115        self.cpu.record(nanos_of(cpu));
116    }
117
118    /// Records what frame `frame` cost on the GPU, ignoring a report already
119    /// recorded.
120    ///
121    /// Reports whether it was a new frame. The caller reads a *latent* report
122    /// that answers with the same frame until the ring comes round, so counting
123    /// every read would fill the window with duplicates of whatever the GPU
124    /// happened to be slow at.
125    pub fn record_gpu(&mut self, frame: u64, gpu: Duration) -> bool {
126        if self.gpu_frame == Some(frame) {
127            return false;
128        }
129        self.gpu_frame = Some(frame);
130        self.gpu.record(nanos_of(gpu));
131        true
132    }
133
134    /// Whether either window holds anything.
135    ///
136    /// What the overlay asks before adding the section: a run that never turned
137    /// the trace on and has no GPU timers has nothing to say here, and three rows
138    /// of `none` in every sample is clutter rather than information.
139    #[must_use]
140    pub fn has_samples(&self) -> bool {
141        !self.cpu.is_empty() || !self.gpu.is_empty()
142    }
143
144    /// The CPU window's p50 and p95, or `None` below
145    /// [`MIN_PERCENTILE_SAMPLES`].
146    #[must_use]
147    pub fn cpu(&self) -> Option<(Duration, Duration)> {
148        self.cpu.percentiles().map(durations_of)
149    }
150
151    /// The GPU window's p50 and p95, or `None` below
152    /// [`MIN_PERCENTILE_SAMPLES`].
153    #[must_use]
154    pub fn gpu(&self) -> Option<(Duration, Duration)> {
155        self.gpu.percentiles().map(durations_of)
156    }
157
158    /// The frame the newest GPU sample came from, which trails the frame being
159    /// drawn by the timers' ring latency.
160    #[must_use]
161    pub const fn gpu_frame(&self) -> Option<u64> {
162        self.gpu_frame
163    }
164
165    /// Which of the two the frame is costing.
166    ///
167    /// **The rule, in full**: the budget is whichever side has the larger p50,
168    /// and it is [`Bound::Unknown`] until *both* windows hold
169    /// [`MIN_PERCENTILE_SAMPLES`]. p50 rather than p95 because the question is
170    /// what a frame normally costs — a p95 comparison answers "which side stalls
171    /// worse", which is a different and rarer question, and the p95s are on the
172    /// row for whoever is asking it.
173    #[must_use]
174    pub fn bound(&self) -> Bound {
175        let (Some((cpu, _)), Some((gpu, _))) = (self.cpu.percentiles(), self.gpu.percentiles())
176        else {
177            return Bound::Unknown;
178        };
179        match gpu.cmp(&cpu) {
180            core::cmp::Ordering::Greater => Bound::Gpu,
181            core::cmp::Ordering::Less => Bound::Cpu,
182            core::cmp::Ordering::Equal => Bound::Tied,
183        }
184    }
185}
186
187/// A window's contribution to the row: its two percentiles, or why it has none.
188fn write_window(out: &mut DebugSection, label: &str, window: &Window) {
189    match window.percentiles() {
190        Some((p50, p95)) => out.row(
191            label,
192            format_args!("{:.2} / {:.2} ms", millis(p50), millis(p95)),
193        ),
194        None if window.is_empty() => out.row_str(label, "none"),
195        // Deliberately not a number: a p95 over this many samples is the
196        // maximum, and printing it as a percentile is the lie this avoids.
197        None => out.row(
198            label,
199            format_args!("filling {}/{}", window.len(), MIN_PERCENTILE_SAMPLES),
200        ),
201    }
202}
203
204fn millis(nanos: u64) -> f64 {
205    nanos as f64 / 1.0e6
206}
207
208fn nanos_of(duration: Duration) -> u64 {
209    u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX)
210}
211
212fn durations_of((p50, p95): (u64, u64)) -> (Duration, Duration) {
213    (Duration::from_nanos(p50), Duration::from_nanos(p95))
214}
215
216/// The row itself.
217///
218/// Labels are deliberately long enough to be unique across the whole panel:
219/// `DebugModule` labels share one namespace and nothing detects a collision, so
220/// a bare `cpu` beside the GPU section's per-pass labels would be a row a reader
221/// — or a test searching the draw list — could pick up as the wrong one.
222impl DebugModule for BudgetStats {
223    fn debug_section(&self, out: &mut DebugSection) {
224        out.set_title("budget");
225        write_window(out, "cpu p50/p95", &self.cpu);
226        write_window(out, "gpu elapsed p50/p95", &self.gpu);
227        out.row_str("bound", self.bound().as_str());
228        match self.gpu_frame {
229            Some(frame) => out.row("gpu frame", format_args!("{frame}")),
230            None => out.row_str("gpu frame", "pending"),
231        }
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238
239    fn ms(millis: u64) -> Duration {
240        Duration::from_millis(millis)
241    }
242
243    /// Fills a window with `n` samples of `millis` each.
244    fn fill(stats: &mut BudgetStats, n: usize, cpu: u64, gpu: u64) {
245        for frame in 0..n {
246            stats.record_cpu(ms(cpu));
247            stats.record_gpu(frame as u64, ms(gpu));
248        }
249    }
250
251    /// **Below the minimum there is no percentile**, and the row says which of
252    /// the two reasons it has none.
253    #[test]
254    fn a_short_window_reports_how_full_it_is_rather_than_a_percentile() {
255        let mut stats = BudgetStats::new();
256        assert!(!stats.has_samples());
257        assert_eq!(stats.cpu(), None);
258        assert_eq!(stats.bound(), Bound::Unknown);
259
260        assert_eq!(rendered(&stats, "cpu p50/p95"), "none");
261        assert_eq!(rendered(&stats, "gpu frame"), "pending");
262
263        fill(&mut stats, MIN_PERCENTILE_SAMPLES - 1, 4, 8);
264        assert!(stats.has_samples());
265        assert_eq!(stats.cpu(), None, "one sample short is still short");
266        assert_eq!(stats.bound(), Bound::Unknown);
267        assert_eq!(rendered(&stats, "cpu p50/p95"), "filling 19/20");
268        assert_eq!(rendered(&stats, "bound"), "unknown");
269
270        // The sample that completes the window is the one that produces a
271        // number: the boundary, not somewhere near it.
272        fill(&mut stats, 1, 4, 8);
273        assert_eq!(stats.cpu(), Some((ms(4), ms(4))));
274        assert_eq!(stats.bound(), Bound::Gpu);
275    }
276
277    /// **The budget rule, both ways round**, so an inverted comparison cannot
278    /// pass by agreeing with itself.
279    #[test]
280    fn the_budget_is_whichever_side_has_the_larger_p50() {
281        let mut gpu_bound = BudgetStats::new();
282        fill(&mut gpu_bound, MIN_PERCENTILE_SAMPLES, 4, 9);
283        assert_eq!(gpu_bound.cpu(), Some((ms(4), ms(4))));
284        assert_eq!(gpu_bound.gpu(), Some((ms(9), ms(9))));
285        assert_eq!(gpu_bound.bound(), Bound::Gpu);
286        assert_eq!(gpu_bound.bound().to_string(), "gpu");
287
288        let mut cpu_bound = BudgetStats::new();
289        fill(&mut cpu_bound, MIN_PERCENTILE_SAMPLES, 9, 4);
290        assert_eq!(cpu_bound.bound(), Bound::Cpu);
291
292        let mut tied = BudgetStats::new();
293        fill(&mut tied, MIN_PERCENTILE_SAMPLES, 5, 5);
294        assert_eq!(tied.bound(), Bound::Tied);
295
296        // One side alone is not an answer, however many samples it has.
297        let mut half = BudgetStats::new();
298        for _ in 0..MIN_PERCENTILE_SAMPLES {
299            half.record_cpu(ms(4));
300        }
301        assert!(half.cpu().is_some());
302        assert_eq!(half.gpu(), None);
303        assert_eq!(half.bound(), Bound::Unknown);
304    }
305
306    /// **The latent GPU report is counted once**, not once per frame it is read.
307    ///
308    /// The ring hands back the same `FrameTimings` until a slot comes round, so a
309    /// window that took every read would be a window of duplicates — and a
310    /// stalled ring would look like a steady frame rate.
311    #[test]
312    fn re_reading_the_same_gpu_frame_does_not_fill_the_window() {
313        let mut stats = BudgetStats::new();
314        assert!(stats.record_gpu(7, ms(3)), "a frame not seen before");
315        assert!(!stats.record_gpu(7, ms(3)), "the same frame again");
316        assert!(!stats.record_gpu(7, ms(99)), "even at a different cost");
317        assert_eq!(stats.gpu.len(), 1);
318        assert_eq!(stats.gpu_frame(), Some(7));
319
320        assert!(stats.record_gpu(8, ms(3)));
321        assert_eq!(stats.gpu.len(), 2);
322        assert_eq!(stats.gpu_frame(), Some(8));
323    }
324
325    /// The window evicts at its bound, so a stall that has scrolled off stops
326    /// counting — and the bound is the frame row's, so the two rows cover the
327    /// same frames.
328    #[test]
329    fn the_window_holds_the_frame_rows_worth_of_frames_and_then_evicts() {
330        let mut stats = BudgetStats::new();
331        // One enormous frame, then a full window of small ones on top of it.
332        stats.record_cpu(ms(500));
333        for _ in 0..DEFAULT_FRAME_WINDOW {
334            stats.record_cpu(ms(4));
335        }
336        assert_eq!(stats.cpu.len(), DEFAULT_FRAME_WINDOW);
337        assert_eq!(
338            stats.cpu(),
339            Some((ms(4), ms(4))),
340            "the 500 ms frame has scrolled out of the window"
341        );
342    }
343
344    /// **The row's text changes when the numbers do.** A row that rendered a
345    /// constant would pass a test that only checked the row existed.
346    #[test]
347    fn the_row_renders_the_numbers_it_was_given() {
348        let mut stats = BudgetStats::new();
349        fill(&mut stats, MIN_PERCENTILE_SAMPLES, 4, 9);
350        let mut section = DebugSection::default();
351        stats.debug_section(&mut section);
352        assert_eq!(section.title(), "budget");
353        assert_eq!(rendered(&stats, "cpu p50/p95"), "4.00 / 4.00 ms");
354        assert_eq!(rendered(&stats, "gpu elapsed p50/p95"), "9.00 / 9.00 ms");
355        assert_eq!(rendered(&stats, "bound"), "gpu");
356        assert_eq!(
357            rendered(&stats, "gpu frame"),
358            (MIN_PERCENTILE_SAMPLES - 1).to_string(),
359        );
360
361        // Different numbers in, different strings out — including the bound.
362        let mut other = BudgetStats::new();
363        for frame in 0..MIN_PERCENTILE_SAMPLES {
364            other.record_cpu(ms(20));
365            other.record_gpu(frame as u64, ms(1));
366        }
367        assert_eq!(rendered(&other, "cpu p50/p95"), "20.00 / 20.00 ms");
368        assert_eq!(rendered(&other, "gpu elapsed p50/p95"), "1.00 / 1.00 ms");
369        assert_eq!(rendered(&other, "bound"), "cpu");
370    }
371
372    /// A spread window, so the two percentiles are actually different numbers
373    /// and the row is not just printing one value twice.
374    #[test]
375    fn the_two_percentiles_are_read_off_the_same_window_separately() {
376        let mut stats = BudgetStats::new();
377        // 1..=20 milliseconds: p50 is the 10th, p95 the 19th.
378        for value in 1..=MIN_PERCENTILE_SAMPLES as u64 {
379            stats.record_cpu(ms(value));
380        }
381        assert_eq!(stats.cpu(), Some((ms(10), ms(19))));
382        assert_eq!(rendered(&stats, "cpu p50/p95"), "10.00 / 19.00 ms");
383    }
384
385    /// Every label this section writes, so a rename is visible and a collision
386    /// with another module's row is something a reader can check against this
387    /// list.
388    #[test]
389    fn the_sections_labels_are_its_own() {
390        let mut section = DebugSection::default();
391        BudgetStats::new().debug_section(&mut section);
392        let labels: Vec<&str> = section
393            .rows()
394            .iter()
395            .map(|row| row.label.as_str())
396            .collect();
397        assert_eq!(
398            labels,
399            ["cpu p50/p95", "gpu elapsed p50/p95", "bound", "gpu frame"],
400        );
401    }
402
403    /// One row's value, by label, off a section written from scratch — the way
404    /// the panel writes one, which clears before every `debug_section`.
405    fn rendered(stats: &BudgetStats, label: &str) -> String {
406        let mut section = DebugSection::default();
407        stats.debug_section(&mut section);
408        section
409            .rows()
410            .iter()
411            .find(|row| row.label == label)
412            .unwrap_or_else(|| panic!("no {label:?} row in {:?}", section.rows()))
413            .value
414            .clone()
415    }
416}