crcbl_render/pass_stats.rs
1//! What each pass costs **over a run**, rather than what one latent frame cost.
2//!
3//! [`crate::timing::PassTimers`] hands back a single [`FrameTimings`] — the
4//! newest frame whose query slot has come back round — and
5//! `crcbl::engine`'s `finish` used to log exactly that as the run's report. One
6//! frame is a sample of one, and the numbers in topic 45's
7//! eleventh decision had to be taken as medians of five hand-run binaries
8//! because nothing in the tree would produce a median of anything. This is the
9//! accumulator that does: every distinct frame's timings go in, and what comes
10//! out is a p50 and a p95 per pass over the last [`DEFAULT_FRAME_WINDOW`] of
11//! them.
12//!
13//! It is deliberately the same shape as [`crcbl_ui::BudgetStats`], which does
14//! this for the frame *total* — the same rolling
15//! [`crcbl_core::stats::Window`], the same floor below which a p95 is
16//! the maximum under another name, and the same guard against counting one
17//! latent report several times. What is new here is the per-pass breakdown,
18//! which is the granularity a quality rung is actually chosen at.
19//!
20//! # A label is summed across the frame, not tracked per occurrence
21//!
22//! A frame draws a label more than once and routinely: `lantern` renders two
23//! views, so `shadow`, `forward` and `tonemap` each appear twice in its report,
24//! and the cull passes appear once per cascade. Recording the occurrences
25//! separately would need a key nothing in the graph provides — position in the
26//! list, which moves whenever a pass is added — so this **sums the occurrences
27//! within one frame** and records one sample per label. The answer is therefore
28//! "what did everything called `forward` cost this frame", which is the
29//! question a budget asks. The occurrence count is on the row so a reader can
30//! see it is more than one.
31//!
32//! # Counts are the newest frame's
33//!
34//! When the timers count each pass's work too (`CRCBL_PASS_STATISTICS=1`, see
35//! [`crate::timing`]), a row also carries what its passes counted, summed over
36//! the label's occurrences like the time. Those are the newest frame's counts,
37//! not a distribution: a scene that does not move counts the same every frame,
38//! and one that does is a sample a reader has to take as one.
39//!
40//! **An occurrence the device could not count is left out of the sum, and the
41//! row says so.** A count that is every stage `None` is a device that cannot
42//! speak for that pass — AMD's D3D12 driver after an amplified draw, see
43//! `crcbl_dx12::command::CountedQuery` — and summing it in would erase the
44//! label's other occurrences with it. So the row carries the sum of the
45//! occurrences that were counted and names how many those were, as "1 of 2
46//! passes counted", which is a smaller claim than the label's whole and says
47//! it is one.
48//!
49//! # What it still does not do
50//!
51//! Fail. Nothing here compares against a recorded baseline, so a rung that
52//! doubles the forward pass shows up in the report and reddens nothing;
53//! `docs/backlog.md` carries that half.
54
55use std::fmt::Write as _;
56
57use crcbl_core::stats::{MIN_PERCENTILE_SAMPLES, Window};
58use crcbl_hal::PipelineStatistics;
59use crcbl_ui::DEFAULT_FRAME_WINDOW;
60
61use crate::timing::{FrameTimings, statistics_columns};
62
63/// One pass label's rolling window.
64#[derive(Clone, Debug)]
65struct Pass {
66 label: String,
67 window: Window<DEFAULT_FRAME_WINDOW>,
68 /// How many times the label appeared in the most recent frame recorded.
69 occurrences: usize,
70 /// What the label's passes counted in the most recent frame that counted
71 /// any of them, summed over those it counted; see the module docs.
72 statistics: Option<PipelineStatistics>,
73 /// How many of that frame's occurrences the sum is of, and how many there
74 /// were.
75 counted: (usize, usize),
76}
77
78/// Two passes' counts as one: each stage summed where both counted it, and
79/// `None` where either could not, since a sum missing a part is not the
80/// label's count.
81fn sum(a: PipelineStatistics, b: PipelineStatistics) -> PipelineStatistics {
82 let add = |a: Option<u64>, b: Option<u64>| Some(a?.saturating_add(b?));
83 PipelineStatistics {
84 input_vertices: add(a.input_vertices, b.input_vertices),
85 input_primitives: add(a.input_primitives, b.input_primitives),
86 vertex_invocations: add(a.vertex_invocations, b.vertex_invocations),
87 clipper_invocations: add(a.clipper_invocations, b.clipper_invocations),
88 clipper_primitives: add(a.clipper_primitives, b.clipper_primitives),
89 fragment_invocations: add(a.fragment_invocations, b.fragment_invocations),
90 compute_invocations: add(a.compute_invocations, b.compute_invocations),
91 task_invocations: add(a.task_invocations, b.task_invocations),
92 mesh_invocations: add(a.mesh_invocations, b.mesh_invocations),
93 mesh_primitives: add(a.mesh_primitives, b.mesh_primitives),
94 }
95}
96
97/// Per-pass GPU cost over a rolling window of frames.
98///
99/// Fed one [`FrameTimings`] a frame — the same latent report the debug overlay
100/// reads — and read at the end of a run, or whenever a caller wants to know
101/// what a pass normally costs rather than what it cost once. See the [module
102/// docs](self).
103#[derive(Clone, Debug, Default)]
104pub struct PassStats {
105 /// One entry per distinct label, in the order the labels were first seen.
106 passes: Vec<Pass>,
107 /// Which frame the newest sample was about, and the guard against counting
108 /// one latent report several times: the ring hands the same `FrameTimings`
109 /// back until a new slot resolves.
110 frame: Option<u64>,
111 /// How many distinct frames have been recorded, which is not the window's
112 /// length once the window is full.
113 frames: u64,
114}
115
116impl PassStats {
117 /// An empty accumulator.
118 #[must_use]
119 pub fn new() -> Self {
120 Self::default()
121 }
122
123 /// Records one frame's per-pass costs, ignoring a report already recorded.
124 ///
125 /// Reports whether it was a new frame. An empty report — a device with no
126 /// timestamps, or a ring that has not come round yet — is not one.
127 pub fn record(&mut self, timings: &FrameTimings) -> bool {
128 if timings.is_empty() || self.frame == Some(timings.frame) {
129 return false;
130 }
131 self.frame = Some(timings.frame);
132 self.frames += 1;
133 // Sum first, record second: a label that appears twice in the frame is
134 // one sample of their total, not two samples of a half each. Cleared
135 // rather than reallocated, so a steady-state frame does not allocate.
136 for pass in &mut self.passes {
137 pass.occurrences = 0;
138 }
139 for timed in &timings.passes {
140 match self
141 .passes
142 .iter_mut()
143 .find(|pass| pass.label == timed.label)
144 {
145 Some(pass) => pass.occurrences += 1,
146 None => self.passes.push(Pass {
147 label: timed.label.clone(),
148 window: Window::new(),
149 occurrences: 1,
150 statistics: None,
151 counted: (0, 0),
152 }),
153 }
154 }
155 for pass in &mut self.passes {
156 if pass.occurrences == 0 {
157 // The pass did not run this frame — a sky that is `Sky::NONE`,
158 // an upscale at full scale. Recording a zero would be a
159 // different claim from not recording, and the wrong one: the
160 // window is what a pass costs *when it runs*.
161 continue;
162 }
163 let nanos = timings
164 .passes
165 .iter()
166 .filter(|timed| timed.label == pass.label)
167 .map(|timed| timed.gpu_nanos)
168 .sum();
169 pass.window.record(nanos);
170 // A frame that counted nothing keeps the last counts rather than
171 // erasing them. An occurrence counted as every stage `None` is one
172 // the device could not count, and is left out; see the module docs.
173 let counts: Vec<PipelineStatistics> = timings
174 .passes
175 .iter()
176 .filter(|timed| timed.label == pass.label)
177 .filter_map(|timed| timed.statistics)
178 .filter(|counted| *counted != PipelineStatistics::default())
179 .collect();
180 let of = counts.len();
181 if let Some(counted) = counts.into_iter().reduce(sum) {
182 pass.statistics = Some(counted);
183 pass.counted = (of, pass.occurrences);
184 }
185 }
186 true
187 }
188
189 /// How many distinct frames have been recorded.
190 #[must_use]
191 pub const fn frames(&self) -> u64 {
192 self.frames
193 }
194
195 /// Whether anything has been recorded at all.
196 #[must_use]
197 pub fn is_empty(&self) -> bool {
198 self.passes.is_empty()
199 }
200
201 /// The labels seen, in the order they were first seen.
202 pub fn labels(&self) -> impl Iterator<Item = &str> {
203 self.passes.iter().map(|pass| pass.label.as_str())
204 }
205
206 /// One pass's p50 and p95 in nanoseconds, or `None` when the label is
207 /// unknown or its window is below [`MIN_PERCENTILE_SAMPLES`].
208 #[must_use]
209 pub fn percentiles(&self, label: &str) -> Option<(u64, u64)> {
210 self.passes
211 .iter()
212 .find(|pass| pass.label == label)?
213 .window
214 .percentiles()
215 }
216
217 /// The sum of every pass's p50.
218 ///
219 /// **Not the p50 of the frame** — that is [`crcbl_ui::BudgetStats`]'s
220 /// number, taken over the totals themselves. This is what the rows add up
221 /// to, which is what the share column is a share of, and the two differ by
222 /// however much the passes' slow frames fail to line up.
223 #[must_use]
224 pub fn p50_total_nanos(&self) -> u64 {
225 self.passes
226 .iter()
227 .filter_map(|pass| pass.window.percentiles())
228 .map(|(p50, _)| p50)
229 .sum()
230 }
231
232 /// The report, as text.
233 ///
234 /// The distribution counterpart of [`FrameTimings::report`]: that says what
235 /// one frame cost, this says what a pass normally costs and how far its tail
236 /// runs.
237 #[must_use]
238 #[allow(clippy::cast_precision_loss)]
239 pub fn report(&self) -> String {
240 if self.passes.is_empty() {
241 return "gpu passes: no GPU timestamps (the device has none)\n".to_string();
242 }
243 let filling = self
244 .passes
245 .iter()
246 .all(|pass| pass.window.percentiles().is_none());
247 if filling {
248 let held = self.passes.first().map_or(0, |pass| pass.window.len());
249 return format!(
250 "gpu passes: filling {held}/{MIN_PERCENTILE_SAMPLES} frames, no percentile yet\n"
251 );
252 }
253 let total = self.p50_total_nanos();
254 let mut out = String::new();
255 let _ = writeln!(
256 out,
257 "gpu passes (p50 / p95 over the last {} of {} frames): \
258 {} label(s), {:.3} ms of p50",
259 DEFAULT_FRAME_WINDOW.min(self.frames as usize),
260 self.frames,
261 self.passes.len(),
262 total as f64 / 1.0e6,
263 );
264 for pass in &self.passes {
265 let Some((p50, p95)) = pass.window.percentiles() else {
266 let _ = writeln!(
267 out,
268 " {:<22} {:>2}x filling {}/{}",
269 pass.label,
270 pass.occurrences,
271 pass.window.len(),
272 MIN_PERCENTILE_SAMPLES
273 );
274 continue;
275 };
276 let share = if total == 0 {
277 0.0
278 } else {
279 p50 as f64 * 100.0 / total as f64
280 };
281 let _ = write!(
282 out,
283 " {:<22} {:>2}x {:>8.3} / {:>8.3} ms {:>5.1}%",
284 pass.label,
285 pass.occurrences,
286 p50 as f64 / 1.0e6,
287 p95 as f64 / 1.0e6,
288 share,
289 );
290 if let Some(statistics) = &pass.statistics {
291 let _ = write!(out, " {}", statistics_columns(statistics));
292 let (counted, of) = pass.counted;
293 if counted < of {
294 let _ = write!(out, " ({counted} of {of} passes counted)");
295 }
296 }
297 out.push('\n');
298 }
299 out
300 }
301}
302
303#[cfg(test)]
304mod tests {
305 use super::*;
306 use crate::timing::PassTiming;
307
308 fn frame(number: u64, passes: &[(&str, u64)]) -> FrameTimings {
309 FrameTimings {
310 elapsed_nanos: None,
311 passes: passes
312 .iter()
313 .map(|(label, gpu_nanos)| PassTiming {
314 label: (*label).to_string(),
315 begin_nanos: 0,
316 gpu_nanos: *gpu_nanos,
317 statistics: None,
318 })
319 .collect(),
320 frame: number,
321 }
322 }
323
324 /// Fills every window past the percentile floor with a constant cost.
325 fn fill(stats: &mut PassStats, frames: u64, passes: &[(&str, u64)]) {
326 for number in 0..frames {
327 stats.record(&frame(number, passes));
328 }
329 }
330
331 /// **The latent report is read every frame and must count once.** The ring
332 /// hands the same `FrameTimings` back until a slot resolves, so a window fed
333 /// from every read would hold duplicates of whatever the GPU was slow at.
334 #[test]
335 fn re_reading_the_same_frame_does_not_fill_the_window() {
336 let mut stats = PassStats::new();
337 let one = frame(7, &[("forward", 1_000)]);
338 assert!(stats.record(&one), "the first read is a new frame");
339 for _ in 0..MIN_PERCENTILE_SAMPLES * 2 {
340 assert!(!stats.record(&one), "the same frame number is not new");
341 }
342 assert_eq!(stats.frames(), 1);
343 assert_eq!(
344 stats.percentiles("forward"),
345 None,
346 "one frame read many times is still one sample"
347 );
348 }
349
350 /// **An empty report is not a frame.** A device with no timestamps and a
351 /// ring that has not come round both hand back an empty `FrameTimings`, and
352 /// recording it as a frame of zero passes would advance the frame count
353 /// past what was measured.
354 #[test]
355 fn an_empty_report_records_nothing() {
356 let mut stats = PassStats::new();
357 assert!(!stats.record(&FrameTimings::default()));
358 assert!(stats.is_empty());
359 assert_eq!(stats.frames(), 0);
360 assert_eq!(
361 stats.report(),
362 "gpu passes: no GPU timestamps (the device has none)\n"
363 );
364 }
365
366 /// **Two occurrences of a label are one sample of their sum.** `lantern`
367 /// renders two views, so this is the shape of every real report the
368 /// accumulator sees.
369 #[test]
370 fn a_label_drawn_twice_is_summed_within_the_frame() {
371 let mut stats = PassStats::new();
372 fill(
373 &mut stats,
374 MIN_PERCENTILE_SAMPLES as u64,
375 &[("forward", 300), ("tonemap", 40), ("forward", 200)],
376 );
377 assert_eq!(stats.percentiles("forward"), Some((500, 500)));
378 assert_eq!(stats.percentiles("tonemap"), Some((40, 40)));
379 assert_eq!(
380 stats.labels().collect::<Vec<_>>(),
381 ["forward", "tonemap"],
382 "a repeated label is one row, in the order it was first seen"
383 );
384 assert_eq!(stats.p50_total_nanos(), 540);
385 let report = stats.report();
386 assert!(report.contains("forward 2x"), "{report}");
387 assert!(report.contains("tonemap 1x"), "{report}");
388 }
389
390 /// **A pass that stops running keeps the window it earned.** A sky set to
391 /// `Sky::NONE` mid-run adds no pass, and recording a zero for it would say
392 /// the pass got cheaper rather than that it went away.
393 #[test]
394 fn a_pass_that_stops_running_records_no_zero() {
395 let mut stats = PassStats::new();
396 fill(
397 &mut stats,
398 MIN_PERCENTILE_SAMPLES as u64,
399 &[("forward", 300), ("sky", 100)],
400 );
401 assert_eq!(stats.percentiles("sky"), Some((100, 100)));
402 for number in 0..MIN_PERCENTILE_SAMPLES as u64 {
403 stats.record(&frame(
404 MIN_PERCENTILE_SAMPLES as u64 + number,
405 &[("forward", 300)],
406 ));
407 }
408 assert_eq!(
409 stats.percentiles("sky"),
410 Some((100, 100)),
411 "the window holds what the pass cost when it ran"
412 );
413 }
414
415 /// **Below the floor the report says so rather than printing a maximum as a
416 /// percentile** — `crcbl_ui::budget`'s rule, and the reason the floor lives
417 /// on the window rather than at each call site.
418 #[test]
419 fn a_short_run_reports_how_full_it_is() {
420 let mut stats = PassStats::new();
421 fill(
422 &mut stats,
423 MIN_PERCENTILE_SAMPLES as u64 - 1,
424 &[("forward", 300_000)],
425 );
426 assert_eq!(stats.percentiles("forward"), None);
427 assert_eq!(
428 stats.report(),
429 "gpu passes: filling 19/20 frames, no percentile yet\n"
430 );
431 stats.record(&frame(999, &[("forward", 300_000)]));
432 let report = stats.report();
433 assert!(
434 report.starts_with(
435 "gpu passes (p50 / p95 over the last 20 of 20 frames): 1 label(s), 0.300 ms of p50"
436 ),
437 "{report}"
438 );
439 assert!(
440 report.contains("forward 1x 0.300 / 0.300 ms 100.0%"),
441 "{report}"
442 );
443 }
444
445 /// **A label that arrives late is still reported**, filling behind the
446 /// others rather than being dropped or silently reported as a maximum.
447 #[test]
448 fn a_late_label_fills_behind_the_others() {
449 let mut stats = PassStats::new();
450 fill(
451 &mut stats,
452 MIN_PERCENTILE_SAMPLES as u64,
453 &[("forward", 300)],
454 );
455 stats.record(&frame(100, &[("forward", 300), ("ssr", 50)]));
456 assert_eq!(stats.percentiles("ssr"), None);
457 let report = stats.report();
458 assert!(
459 report.contains("ssr 1x filling 1/20"),
460 "{report}"
461 );
462 }
463
464 /// **A label's counts are its passes' sum, from the newest frame that
465 /// counted them all.** A frame whose passes were not counted keeps the
466 /// counts already held, and a stage one occurrence could not count is
467 /// `None` in the sum rather than a part passed off as the whole.
468 #[test]
469 fn a_labels_counts_sum_its_passes_and_survive_an_uncounted_frame() {
470 use crcbl_hal::PipelineStatistics;
471
472 let counted = |vertices: u64, task: Option<u64>| PipelineStatistics {
473 vertex_invocations: Some(vertices),
474 task_invocations: task,
475 ..PipelineStatistics::default()
476 };
477 let pass = |statistics| PassTiming {
478 label: "shadow".to_string(),
479 begin_nanos: 0,
480 gpu_nanos: 1_000,
481 statistics,
482 };
483 let mut stats = PassStats::new();
484 stats.record(&FrameTimings {
485 elapsed_nanos: None,
486 frame: 1,
487 passes: vec![
488 pass(Some(counted(3, Some(1)))),
489 pass(Some(counted(4, None))),
490 ],
491 });
492 assert_eq!(
493 stats.passes[0].statistics,
494 Some(PipelineStatistics {
495 vertex_invocations: Some(7),
496 task_invocations: None,
497 ..PipelineStatistics::default()
498 })
499 );
500 stats.record(&FrameTimings {
501 elapsed_nanos: None,
502 frame: 2,
503 passes: vec![pass(None), pass(None)],
504 });
505 assert_eq!(
506 stats.passes[0]
507 .statistics
508 .and_then(|s| s.vertex_invocations),
509 Some(7),
510 "an uncounted frame keeps the counts"
511 );
512 fill(
513 &mut stats,
514 MIN_PERCENTILE_SAMPLES as u64 + 3,
515 &[("shadow", 1_000)],
516 );
517 let report = stats.report();
518 assert!(report.contains("vs 7"), "{report}");
519 }
520
521 /// **An occurrence the device could not count is left out, and the row
522 /// says how many were counted**, rather than the label losing its counts.
523 #[test]
524 fn a_label_with_an_uncountable_pass_reports_the_ones_counted() {
525 use crcbl_hal::PipelineStatistics;
526
527 let pass = |statistics| PassTiming {
528 label: "forward".to_string(),
529 begin_nanos: 0,
530 gpu_nanos: 1_000,
531 statistics: Some(statistics),
532 };
533 let counted = PipelineStatistics {
534 fragment_invocations: Some(689_723),
535 ..PipelineStatistics::default()
536 };
537 let mut stats = PassStats::new();
538 for number in 0..MIN_PERCENTILE_SAMPLES as u64 + 3 {
539 stats.record(&FrameTimings {
540 elapsed_nanos: None,
541 frame: number,
542 passes: vec![pass(counted), pass(PipelineStatistics::default())],
543 });
544 }
545 assert_eq!(stats.passes[0].statistics, Some(counted));
546 let report = stats.report();
547 assert!(
548 report.contains("fs 689723 (1 of 2 passes counted)"),
549 "{report}"
550 );
551
552 // Every occurrence counted: no qualifier.
553 let mut whole = PassStats::new();
554 for number in 0..MIN_PERCENTILE_SAMPLES as u64 + 3 {
555 whole.record(&FrameTimings {
556 elapsed_nanos: None,
557 frame: number,
558 passes: vec![pass(counted), pass(counted)],
559 });
560 }
561 let report = whole.report();
562 assert!(report.contains("fs 1379446"), "{report}");
563 assert!(!report.contains("passes counted"), "{report}");
564 }
565}