use std::fmt::Write as _;
use crcbl_core::stats::{MIN_PERCENTILE_SAMPLES, Window};
use crcbl_hal::PipelineStatistics;
use crcbl_ui::DEFAULT_FRAME_WINDOW;
use crate::timing::{FrameTimings, statistics_columns};
#[derive(Clone, Debug)]
struct Pass {
label: String,
window: Window<DEFAULT_FRAME_WINDOW>,
occurrences: usize,
statistics: Option<PipelineStatistics>,
counted: (usize, usize),
}
fn sum(a: PipelineStatistics, b: PipelineStatistics) -> PipelineStatistics {
let add = |a: Option<u64>, b: Option<u64>| Some(a?.saturating_add(b?));
PipelineStatistics {
input_vertices: add(a.input_vertices, b.input_vertices),
input_primitives: add(a.input_primitives, b.input_primitives),
vertex_invocations: add(a.vertex_invocations, b.vertex_invocations),
clipper_invocations: add(a.clipper_invocations, b.clipper_invocations),
clipper_primitives: add(a.clipper_primitives, b.clipper_primitives),
fragment_invocations: add(a.fragment_invocations, b.fragment_invocations),
compute_invocations: add(a.compute_invocations, b.compute_invocations),
task_invocations: add(a.task_invocations, b.task_invocations),
mesh_invocations: add(a.mesh_invocations, b.mesh_invocations),
mesh_primitives: add(a.mesh_primitives, b.mesh_primitives),
}
}
#[derive(Clone, Debug, Default)]
pub struct PassStats {
passes: Vec<Pass>,
frame: Option<u64>,
frames: u64,
}
impl PassStats {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn record(&mut self, timings: &FrameTimings) -> bool {
if timings.is_empty() || self.frame == Some(timings.frame) {
return false;
}
self.frame = Some(timings.frame);
self.frames += 1;
for pass in &mut self.passes {
pass.occurrences = 0;
}
for timed in &timings.passes {
match self
.passes
.iter_mut()
.find(|pass| pass.label == timed.label)
{
Some(pass) => pass.occurrences += 1,
None => self.passes.push(Pass {
label: timed.label.clone(),
window: Window::new(),
occurrences: 1,
statistics: None,
counted: (0, 0),
}),
}
}
for pass in &mut self.passes {
if pass.occurrences == 0 {
continue;
}
let nanos = timings
.passes
.iter()
.filter(|timed| timed.label == pass.label)
.map(|timed| timed.gpu_nanos)
.sum();
pass.window.record(nanos);
let counts: Vec<PipelineStatistics> = timings
.passes
.iter()
.filter(|timed| timed.label == pass.label)
.filter_map(|timed| timed.statistics)
.filter(|counted| *counted != PipelineStatistics::default())
.collect();
let of = counts.len();
if let Some(counted) = counts.into_iter().reduce(sum) {
pass.statistics = Some(counted);
pass.counted = (of, pass.occurrences);
}
}
true
}
#[must_use]
pub const fn frames(&self) -> u64 {
self.frames
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.passes.is_empty()
}
pub fn labels(&self) -> impl Iterator<Item = &str> {
self.passes.iter().map(|pass| pass.label.as_str())
}
#[must_use]
pub fn percentiles(&self, label: &str) -> Option<(u64, u64)> {
self.passes
.iter()
.find(|pass| pass.label == label)?
.window
.percentiles()
}
#[must_use]
pub fn p50_total_nanos(&self) -> u64 {
self.passes
.iter()
.filter_map(|pass| pass.window.percentiles())
.map(|(p50, _)| p50)
.sum()
}
#[must_use]
#[allow(clippy::cast_precision_loss)]
pub fn report(&self) -> String {
if self.passes.is_empty() {
return "gpu passes: no GPU timestamps (the device has none)\n".to_string();
}
let filling = self
.passes
.iter()
.all(|pass| pass.window.percentiles().is_none());
if filling {
let held = self.passes.first().map_or(0, |pass| pass.window.len());
return format!(
"gpu passes: filling {held}/{MIN_PERCENTILE_SAMPLES} frames, no percentile yet\n"
);
}
let total = self.p50_total_nanos();
let mut out = String::new();
let _ = writeln!(
out,
"gpu passes (p50 / p95 over the last {} of {} frames): \
{} label(s), {:.3} ms of p50",
DEFAULT_FRAME_WINDOW.min(self.frames as usize),
self.frames,
self.passes.len(),
total as f64 / 1.0e6,
);
for pass in &self.passes {
let Some((p50, p95)) = pass.window.percentiles() else {
let _ = writeln!(
out,
" {:<22} {:>2}x filling {}/{}",
pass.label,
pass.occurrences,
pass.window.len(),
MIN_PERCENTILE_SAMPLES
);
continue;
};
let share = if total == 0 {
0.0
} else {
p50 as f64 * 100.0 / total as f64
};
let _ = write!(
out,
" {:<22} {:>2}x {:>8.3} / {:>8.3} ms {:>5.1}%",
pass.label,
pass.occurrences,
p50 as f64 / 1.0e6,
p95 as f64 / 1.0e6,
share,
);
if let Some(statistics) = &pass.statistics {
let _ = write!(out, " {}", statistics_columns(statistics));
let (counted, of) = pass.counted;
if counted < of {
let _ = write!(out, " ({counted} of {of} passes counted)");
}
}
out.push('\n');
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::timing::PassTiming;
fn frame(number: u64, passes: &[(&str, u64)]) -> FrameTimings {
FrameTimings {
elapsed_nanos: None,
passes: passes
.iter()
.map(|(label, gpu_nanos)| PassTiming {
label: (*label).to_string(),
begin_nanos: 0,
gpu_nanos: *gpu_nanos,
statistics: None,
})
.collect(),
frame: number,
}
}
fn fill(stats: &mut PassStats, frames: u64, passes: &[(&str, u64)]) {
for number in 0..frames {
stats.record(&frame(number, passes));
}
}
#[test]
fn re_reading_the_same_frame_does_not_fill_the_window() {
let mut stats = PassStats::new();
let one = frame(7, &[("forward", 1_000)]);
assert!(stats.record(&one), "the first read is a new frame");
for _ in 0..MIN_PERCENTILE_SAMPLES * 2 {
assert!(!stats.record(&one), "the same frame number is not new");
}
assert_eq!(stats.frames(), 1);
assert_eq!(
stats.percentiles("forward"),
None,
"one frame read many times is still one sample"
);
}
#[test]
fn an_empty_report_records_nothing() {
let mut stats = PassStats::new();
assert!(!stats.record(&FrameTimings::default()));
assert!(stats.is_empty());
assert_eq!(stats.frames(), 0);
assert_eq!(
stats.report(),
"gpu passes: no GPU timestamps (the device has none)\n"
);
}
#[test]
fn a_label_drawn_twice_is_summed_within_the_frame() {
let mut stats = PassStats::new();
fill(
&mut stats,
MIN_PERCENTILE_SAMPLES as u64,
&[("forward", 300), ("tonemap", 40), ("forward", 200)],
);
assert_eq!(stats.percentiles("forward"), Some((500, 500)));
assert_eq!(stats.percentiles("tonemap"), Some((40, 40)));
assert_eq!(
stats.labels().collect::<Vec<_>>(),
["forward", "tonemap"],
"a repeated label is one row, in the order it was first seen"
);
assert_eq!(stats.p50_total_nanos(), 540);
let report = stats.report();
assert!(report.contains("forward 2x"), "{report}");
assert!(report.contains("tonemap 1x"), "{report}");
}
#[test]
fn a_pass_that_stops_running_records_no_zero() {
let mut stats = PassStats::new();
fill(
&mut stats,
MIN_PERCENTILE_SAMPLES as u64,
&[("forward", 300), ("sky", 100)],
);
assert_eq!(stats.percentiles("sky"), Some((100, 100)));
for number in 0..MIN_PERCENTILE_SAMPLES as u64 {
stats.record(&frame(
MIN_PERCENTILE_SAMPLES as u64 + number,
&[("forward", 300)],
));
}
assert_eq!(
stats.percentiles("sky"),
Some((100, 100)),
"the window holds what the pass cost when it ran"
);
}
#[test]
fn a_short_run_reports_how_full_it_is() {
let mut stats = PassStats::new();
fill(
&mut stats,
MIN_PERCENTILE_SAMPLES as u64 - 1,
&[("forward", 300_000)],
);
assert_eq!(stats.percentiles("forward"), None);
assert_eq!(
stats.report(),
"gpu passes: filling 19/20 frames, no percentile yet\n"
);
stats.record(&frame(999, &[("forward", 300_000)]));
let report = stats.report();
assert!(
report.starts_with(
"gpu passes (p50 / p95 over the last 20 of 20 frames): 1 label(s), 0.300 ms of p50"
),
"{report}"
);
assert!(
report.contains("forward 1x 0.300 / 0.300 ms 100.0%"),
"{report}"
);
}
#[test]
fn a_late_label_fills_behind_the_others() {
let mut stats = PassStats::new();
fill(
&mut stats,
MIN_PERCENTILE_SAMPLES as u64,
&[("forward", 300)],
);
stats.record(&frame(100, &[("forward", 300), ("ssr", 50)]));
assert_eq!(stats.percentiles("ssr"), None);
let report = stats.report();
assert!(
report.contains("ssr 1x filling 1/20"),
"{report}"
);
}
#[test]
fn a_labels_counts_sum_its_passes_and_survive_an_uncounted_frame() {
use crcbl_hal::PipelineStatistics;
let counted = |vertices: u64, task: Option<u64>| PipelineStatistics {
vertex_invocations: Some(vertices),
task_invocations: task,
..PipelineStatistics::default()
};
let pass = |statistics| PassTiming {
label: "shadow".to_string(),
begin_nanos: 0,
gpu_nanos: 1_000,
statistics,
};
let mut stats = PassStats::new();
stats.record(&FrameTimings {
elapsed_nanos: None,
frame: 1,
passes: vec![
pass(Some(counted(3, Some(1)))),
pass(Some(counted(4, None))),
],
});
assert_eq!(
stats.passes[0].statistics,
Some(PipelineStatistics {
vertex_invocations: Some(7),
task_invocations: None,
..PipelineStatistics::default()
})
);
stats.record(&FrameTimings {
elapsed_nanos: None,
frame: 2,
passes: vec![pass(None), pass(None)],
});
assert_eq!(
stats.passes[0]
.statistics
.and_then(|s| s.vertex_invocations),
Some(7),
"an uncounted frame keeps the counts"
);
fill(
&mut stats,
MIN_PERCENTILE_SAMPLES as u64 + 3,
&[("shadow", 1_000)],
);
let report = stats.report();
assert!(report.contains("vs 7"), "{report}");
}
#[test]
fn a_label_with_an_uncountable_pass_reports_the_ones_counted() {
use crcbl_hal::PipelineStatistics;
let pass = |statistics| PassTiming {
label: "forward".to_string(),
begin_nanos: 0,
gpu_nanos: 1_000,
statistics: Some(statistics),
};
let counted = PipelineStatistics {
fragment_invocations: Some(689_723),
..PipelineStatistics::default()
};
let mut stats = PassStats::new();
for number in 0..MIN_PERCENTILE_SAMPLES as u64 + 3 {
stats.record(&FrameTimings {
elapsed_nanos: None,
frame: number,
passes: vec![pass(counted), pass(PipelineStatistics::default())],
});
}
assert_eq!(stats.passes[0].statistics, Some(counted));
let report = stats.report();
assert!(
report.contains("fs 689723 (1 of 2 passes counted)"),
"{report}"
);
let mut whole = PassStats::new();
for number in 0..MIN_PERCENTILE_SAMPLES as u64 + 3 {
whole.record(&FrameTimings {
elapsed_nanos: None,
frame: number,
passes: vec![pass(counted), pass(counted)],
});
}
let report = whole.report();
assert!(report.contains("fs 1379446"), "{report}");
assert!(!report.contains("passes counted"), "{report}");
}
}