use core::fmt::Write as _;
use crcbl_hal::{
CommandEncoder, Device, Features, PassStatisticsWrites, PassTimestampWrites,
PipelineStatistics, QueryKind, QuerySetDesc, QuerySetHandle,
};
use crcbl_ui::debug::{DebugModule, DebugSection};
use crate::graph::{CompiledPass, PassKind};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PassTiming {
pub label: String,
pub begin_nanos: u64,
pub gpu_nanos: u64,
pub statistics: Option<PipelineStatistics>,
}
pub const STATISTICS_VAR: &str = "CRCBL_PASS_STATISTICS";
fn statistics_wanted(value: Option<&str>) -> bool {
value.map(str::trim) == Some("1")
}
#[must_use]
pub fn statistics_requested() -> bool {
statistics_wanted(std::env::var(STATISTICS_VAR).ok().as_deref())
}
#[must_use]
pub fn statistics_columns(statistics: &PipelineStatistics) -> String {
let columns = [
("ia-vtx", statistics.input_vertices),
("ia-prim", statistics.input_primitives),
("vs", statistics.vertex_invocations),
("clip", statistics.clipper_invocations),
("clip-out", statistics.clipper_primitives),
("fs", statistics.fragment_invocations),
("cs", statistics.compute_invocations),
("task", statistics.task_invocations),
("mesh", statistics.mesh_invocations),
("mesh-prim", statistics.mesh_primitives),
];
let mut out = String::new();
for (name, count) in columns {
if let Some(count) = count {
if !out.is_empty() {
out.push(' ');
}
let _ = write!(out, "{name} {count}");
}
}
out
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FrameTimings {
pub passes: Vec<PassTiming>,
pub frame: u64,
pub elapsed_nanos: Option<u64>,
}
impl FrameTimings {
#[must_use]
pub fn total_nanos(&self) -> u64 {
self.passes.iter().map(|pass| pass.gpu_nanos).sum()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.passes.is_empty()
}
#[must_use]
pub fn report(&self) -> String {
if self.passes.is_empty() {
return "frame timing: no GPU timestamps (the device has none)\n".to_string();
}
let mut out = String::new();
let total = self.total_nanos();
let _ = writeln!(
out,
"frame timing (frame {}): {} pass(es), {:.3} ms sum of pass spans",
self.frame,
self.passes.len(),
total as f64 / 1.0e6
);
if let Some(elapsed) = self.elapsed_nanos {
let _ = writeln!(
out,
" measured GPU elapsed: {:.3} ms",
elapsed as f64 / 1.0e6
);
}
for pass in &self.passes {
let share = if total == 0 {
0.0
} else {
pass.gpu_nanos as f64 * 100.0 / total as f64
};
let _ = write!(
out,
" {:<24} {:>9.3} ms {:>5.1}%",
pass.label,
pass.gpu_nanos as f64 / 1.0e6,
share
);
if let Some(statistics) = &pass.statistics {
let _ = write!(out, " {}", statistics_columns(statistics));
}
out.push('\n');
}
out
}
}
impl DebugModule for FrameTimings {
fn debug_section(&self, out: &mut DebugSection) {
out.set_title("gpu");
if self.passes.is_empty() {
out.row_str("timings", "pending");
return;
}
for pass in &self.passes {
out.row(
&pass.label,
format_args!("{:.3} ms", pass.gpu_nanos as f64 / 1.0e6),
);
}
out.row(
"span sum",
format_args!("{:.3} ms", self.total_nanos() as f64 / 1.0e6),
);
if let Some(elapsed) = self.elapsed_nanos {
out.row("elapsed", format_args!("{:.3} ms", elapsed as f64 / 1.0e6));
}
out.row("frame", format_args!("{}", self.frame));
}
}
#[derive(Debug)]
struct Slot {
set: QuerySetHandle,
statistics: Option<QuerySetHandle>,
labels: Vec<String>,
frame: u64,
}
#[derive(Debug)]
pub struct PassTimers {
slots: Vec<Slot>,
current: usize,
pairs: Vec<Option<u32>>,
capacity: u32,
frames: u64,
latest: FrameTimings,
warned: bool,
}
impl PassTimers {
#[must_use]
pub fn new(device: &dyn Device, frames_in_flight: usize, max_passes: u32) -> Option<Self> {
Self::create(device, frames_in_flight, max_passes, statistics_requested())
}
#[must_use]
pub fn counting(device: &dyn Device, frames_in_flight: usize, max_passes: u32) -> Option<Self> {
Self::create(device, frames_in_flight, max_passes, true)
}
fn create(
device: &dyn Device,
frames_in_flight: usize,
max_passes: u32,
counted: bool,
) -> Option<Self> {
if !device.caps().features.contains(Features::TIMESTAMP_QUERY) {
crcbl_core::log::debug!(
"graph: no TIMESTAMP_QUERY on this device; per-pass timing is off"
);
return None;
}
let Some(query_count) = max_passes.checked_mul(2) else {
crcbl_core::log::debug!(
"graph: {max_passes} passes needs {} timestamp queries, more than a u32 index \
holds; per-pass timing is off",
u64::from(max_passes) * 2
);
return None;
};
let counted = counted && {
let able = device
.caps()
.features
.contains(Features::PIPELINE_STATISTICS_QUERY);
if !able {
crcbl_core::log::info!(
"graph: passes were to be counted and this device has no \
PIPELINE_STATISTICS_QUERY; they are timed, not counted"
);
}
able
};
let count = frames_in_flight + 2;
let mut slots: Vec<Slot> = Vec::with_capacity(count);
let refused = |slots: &[Slot], what: &str, index: usize, error: crcbl_hal::HalError| {
crcbl_core::log::debug!("graph: {what} set {index} refused ({error}); timing is off");
for slot in slots {
device.destroy_query_set(slot.set);
if let Some(statistics) = slot.statistics {
device.destroy_query_set(statistics);
}
}
};
for index in 0..count {
let set = match device.create_query_set(&QuerySetDesc {
label: Some("graph pass timers"),
kind: QueryKind::Timestamp,
count: query_count,
}) {
Ok(set) => set,
Err(error) => {
refused(&slots, "timestamp", index, error);
return None;
}
};
let statistics = if counted {
match device.create_query_set(&QuerySetDesc {
label: Some("graph pass statistics"),
kind: QueryKind::PipelineStatistics,
count: max_passes,
}) {
Ok(statistics) => Some(statistics),
Err(error) => {
device.destroy_query_set(set);
refused(&slots, "statistics", index, error);
return None;
}
}
} else {
None
};
slots.push(Slot {
set,
statistics,
labels: Vec::new(),
frame: 0,
});
}
Some(Self {
slots,
current: 0,
pairs: Vec::new(),
capacity: max_passes,
frames: 0,
latest: FrameTimings::default(),
warned: false,
})
}
#[must_use]
pub fn latest(&self) -> &FrameTimings {
&self.latest
}
#[must_use]
pub const fn capacity(&self) -> u32 {
self.capacity
}
pub(crate) fn begin_frame(
&mut self,
device: &dyn Device,
encoder: &mut dyn CommandEncoder,
passes: &[CompiledPass<'_>],
) {
self.frames += 1;
self.current = (self.current + 1) % self.slots.len();
let next = (self.current + 1) % self.slots.len();
self.resolve(device, next);
let timeable = passes
.iter()
.filter(|pass| pass.kind() != PassKind::Copy)
.count();
let used = timeable.min(self.capacity as usize);
if timeable > used && !self.warned {
self.warned = true;
crcbl_core::log::warn!(
"graph: {timeable} timed passes but timers hold {}; the last {} are untimed (said \
once)",
self.capacity,
timeable - used
);
}
let slot = &mut self.slots[self.current];
slot.labels.clear();
self.pairs.clear();
for pass in passes {
let pair = if pass.kind() == PassKind::Copy {
None
} else {
let next = u32::try_from(slot.labels.len()).unwrap_or(u32::MAX);
(next < self.capacity).then(|| {
slot.labels.push(pass.label().to_string());
next
})
};
self.pairs.push(pair);
}
slot.frame = self.frames;
encoder.reset_query_set(slot.set, 0..self.capacity.saturating_mul(2));
let ahead = self.slots[next].statistics;
let behind = self.slots[self.current]
.statistics
.filter(|_| self.frames == 1);
for statistics in behind.into_iter().chain(ahead) {
encoder.reset_query_set(statistics, 0..self.capacity);
}
}
pub(crate) fn pass_writes(&self, index: usize) -> Option<PassTimestampWrites> {
let pair = *self.pairs.get(index)?;
pair.map(|pair| PassTimestampWrites {
set: self.slots[self.current].set,
beginning_of_pass: pair * 2,
end_of_pass: pair * 2 + 1,
})
}
pub(crate) fn pass_statistics(&self, index: usize) -> Option<PassStatisticsWrites> {
let pair = (*self.pairs.get(index)?)?;
let set = self.slots[self.current].statistics?;
Some(PassStatisticsWrites { set, query: pair })
}
fn resolve(&mut self, device: &dyn Device, index: usize) {
let slot = &self.slots[index];
if slot.labels.is_empty() {
return;
}
let mut nanos = vec![0u64; slot.labels.len() * 2];
if let Err(error) = device.query_results(slot.set, 0, &mut nanos) {
crcbl_core::log::debug!(
"graph: timestamp read failed ({error}); dropping this frame's timing"
);
return;
}
let counts = slot.statistics.and_then(|set| {
let mut counts = vec![PipelineStatistics::default(); slot.labels.len()];
match device.pipeline_statistics(set, 0, &mut counts) {
Ok(()) => Some(counts),
Err(error) => {
crcbl_core::log::debug!(
"graph: statistics read failed ({error}); this frame is timed, not \
counted"
);
None
}
}
});
let passes = slot
.labels
.iter()
.enumerate()
.map(|(index, label)| {
PassTiming {
label: label.clone(),
begin_nanos: nanos[index * 2],
gpu_nanos: nanos[index * 2 + 1].saturating_sub(nanos[index * 2]),
statistics: counts.as_ref().map(|counts| counts[index]),
}
})
.collect();
self.latest = FrameTimings {
passes,
frame: slot.frame,
elapsed_nanos: measured_span(&nanos),
};
}
pub fn destroy(&mut self, device: &dyn Device) {
for slot in &self.slots {
device.destroy_query_set(slot.set);
if let Some(statistics) = slot.statistics {
device.destroy_query_set(statistics);
}
}
self.slots.clear();
}
}
fn measured_span(nanos: &[u64]) -> Option<u64> {
if nanos.is_empty() || !nanos.len().is_multiple_of(2) {
return None;
}
let mut first = u64::MAX;
let mut last = 0;
for pair in nanos.as_chunks::<2>().0 {
let (start, end) = (pair[0], pair[1]);
if start == 0 || end < start {
return None;
}
first = first.min(start);
last = last.max(end);
}
Some(last - first)
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
#[test]
fn overlapping_passes_measure_the_outer_interval_not_their_sum() {
assert_eq!(measured_span(&[100, 500, 200, 900]), Some(800));
assert_eq!(measured_span(&[100, 200, 400, 700]), Some(600));
assert_eq!(measured_span(&[500, 500]), Some(0));
}
#[test]
fn a_missing_or_backwards_timestamp_cannot_supply_a_budget() {
for values in [
&[][..],
&[100][..],
&[0, 200][..],
&[100, 0][..],
&[200, 100][..],
] {
assert_eq!(measured_span(values), None);
}
assert_eq!(measured_span(&[100, 200, 0, 400]), None);
}
#[test]
fn an_empty_report_says_so_rather_than_printing_nothing() {
let timings = FrameTimings::default();
assert!(timings.is_empty());
assert_eq!(timings.total_nanos(), 0);
assert!(timings.report().contains("no GPU timestamps"));
}
#[test]
fn the_report_lists_every_pass_with_its_share() {
let timings = FrameTimings {
elapsed_nanos: None,
frame: 42,
passes: vec![
PassTiming {
label: "forward".to_string(),
begin_nanos: 0,
gpu_nanos: 3_000_000,
statistics: None,
},
PassTiming {
label: "tonemap".to_string(),
begin_nanos: 0,
gpu_nanos: 1_000_000,
statistics: None,
},
],
};
assert_eq!(timings.total_nanos(), 4_000_000);
let report = timings.report();
assert!(report.contains("frame 42"), "{report}");
assert!(report.contains("forward"), "{report}");
assert!(report.contains("tonemap"), "{report}");
assert!(report.contains("4.000 ms"), "{report}");
assert!(
report.contains("75.0%"),
"the shares must be there: {report}"
);
assert!(report.contains("25.0%"), "{report}");
}
#[test]
fn a_counted_pass_reports_the_stages_it_counted() {
let statistics = PipelineStatistics {
vertex_invocations: Some(3),
fragment_invocations: Some(788),
task_invocations: Some(0),
mesh_invocations: None,
..PipelineStatistics::default()
};
assert_eq!(statistics_columns(&statistics), "vs 3 fs 788 task 0");
assert_eq!(statistics_columns(&PipelineStatistics::default()), "");
let timings = FrameTimings {
elapsed_nanos: None,
frame: 3,
passes: vec![
PassTiming {
label: "depth".to_string(),
begin_nanos: 0,
gpu_nanos: 1_000_000,
statistics: Some(statistics),
},
PassTiming {
label: "tonemap".to_string(),
begin_nanos: 0,
gpu_nanos: 1_000_000,
statistics: None,
},
],
};
let report = timings.report();
let depth = report
.lines()
.find(|line| line.contains("depth"))
.expect("a depth row");
assert!(depth.ends_with(" vs 3 fs 788 task 0"), "{report}");
let tonemap = report
.lines()
.find(|line| line.contains("tonemap"))
.expect("a tonemap row");
assert!(
tonemap.ends_with('%'),
"an uncounted pass has no columns: {report}"
);
}
#[test]
fn only_a_one_asks_for_the_counts() {
assert!(statistics_wanted(Some("1")));
assert!(statistics_wanted(Some(" 1 ")));
for value in [None, Some(""), Some("0"), Some("true"), Some("yes")] {
assert!(!statistics_wanted(value), "{value:?}");
}
}
#[test]
fn a_zero_length_frame_reports_zero_shares_rather_than_nan() {
let timings = FrameTimings {
elapsed_nanos: None,
frame: 1,
passes: vec![PassTiming {
label: "clear".to_string(),
begin_nanos: 0,
gpu_nanos: 0,
statistics: None,
}],
};
let report = timings.report();
assert!(!report.contains("NaN"), "{report}");
assert!(report.contains("0.0%"), "{report}");
}
#[test]
fn the_debug_section_carries_the_passes_the_renderer_reported() {
use crcbl_ui::debug::{DebugOverlay, DebugRow};
use crcbl_ui::draw_list::{DrawCommand, DrawList};
use crcbl_ui::text::FontAtlas;
use glam::Vec2;
let timings = FrameTimings {
elapsed_nanos: None,
frame: 7,
passes: vec![
PassTiming {
label: "sprites".to_string(),
begin_nanos: 0,
gpu_nanos: 2_500_000,
statistics: None,
},
PassTiming {
label: "ui".to_string(),
begin_nanos: 0,
gpu_nanos: 250_000,
statistics: None,
},
],
};
let mut section = DebugSection::default();
timings.debug_section(&mut section);
assert_eq!(section.title(), "gpu");
let rows: Vec<(&str, &str)> = section
.rows()
.iter()
.map(|DebugRow { label, value }| (label.as_str(), value.as_str()))
.collect();
assert_eq!(
rows,
[
("sprites", "2.500 ms"),
("ui", "0.250 ms"),
("span sum", "2.750 ms"),
("frame", "7"),
],
);
let mut overlay = DebugOverlay::with_visible(true);
overlay.record(core::time::Duration::from_millis(16));
overlay.begin_frame();
overlay.add(&timings);
let mut dl = DrawList::new();
overlay.render(&mut dl, Vec2::new(1280.0, 720.0), &FontAtlas::built_in());
let drawn: Vec<&str> = dl
.commands()
.iter()
.filter_map(|command| match command {
DrawCommand::Text { text, .. } => Some(text.as_str()),
_ => None,
})
.collect();
assert_eq!(drawn.first(), Some(&"frame"), "{drawn:?}");
let gpu = drawn
.iter()
.position(|text| *text == "gpu")
.expect("the gpu section is drawn");
assert_eq!(
&drawn[gpu..],
[
"gpu", "sprites", "2.500 ms", "ui", "0.250 ms", "span sum", "2.750 ms", "frame",
"7",
],
);
}
#[test]
fn a_latent_report_renders_as_pending_rather_than_zero() {
let mut section = DebugSection::default();
FrameTimings::default().debug_section(&mut section);
assert_eq!(section.title(), "gpu");
assert_eq!(section.rows().len(), 1);
assert_eq!(section.rows()[0].value, "pending");
}
#[test]
fn a_device_without_timestamps_gets_no_timers_and_no_error() {
use crcbl_hal::null::NullInstance;
use crcbl_hal::{DeviceDesc, Instance};
let instance = NullInstance::portable();
let adapter = instance.adapters().remove(0);
let device = instance
.create_device(&DeviceDesc {
label: None,
adapter: adapter.id,
required_features: Features::empty(),
optional_features: Features::empty(),
compatible_surface: None,
})
.expect("the null backend always opens");
assert!(
!device.caps().features.contains(Features::TIMESTAMP_QUERY),
"this test is only meaningful against a device that has none"
);
assert!(
PassTimers::new(device.as_ref(), 2, 8).is_none(),
"timers must decline rather than fail"
);
}
}