Skip to main content

crcbl_frame/
timing.rs

1//! Per-pass GPU timestamps, and the frame-timing report they feed.
2//!
3//! Stage 2 §2.4's last bullet: "GPU timestamp per pass,
4//! exposed as a frame-timing report (feeds the stage 7 profiler HUD)". This is
5//! that, and it is wired into [`CompiledGraph::execute`](crate::graph::CompiledGraph::execute)
6//! rather than bolted on, which is the stated reason (`docs/notes/backends.md`)
7//! for putting timestamp queries in the seam at P0: "a profiler bolted on
8//! afterwards is one that never covers the passes written before it".
9//!
10//! # The report is frames latent, on purpose
11//!
12//! Reading a timestamp the GPU has not written yet is either a stall or a lie.
13//! So the timers keep a ring of query sets — one more than the frames the loop
14//! keeps in flight — and resolve a slot only when it comes back round, by which
15//! point the submission that wrote it has certainly completed. The report is
16//! therefore about a frame a few frames ago, which is exactly what a profiler
17//! HUD wants and exactly the shape topic 03 §3.6
18//! calls for ("N frames latent").
19//!
20//! No fence, no wait, no `wait_idle`: the latency *is* the synchronisation.
21//!
22//! # Timestamps are the pass's own boundaries, and a copy pass has none
23//!
24//! The seam has no free-standing timestamp: two queries are named by the pass
25//! descriptor itself, as [`PassTimestampWrites`], and the backend takes them
26//! where the pass opens and closes. So the number reported for a pass is the
27//! pass alone, and the barriers the graph inserted around it are attributed to
28//! nothing. That is a narrower number than the one this reported before — the
29//! seam used to bracket each pass from before its barriers to after its close —
30//! and it is the only one every backend can produce, because Metal samples at
31//! stage boundaries and WebGPU only through `timestampWrites`.
32//!
33//! It also means a [`PassKind::Copy`](crate::graph::PassKind) pass is not
34//! timed at all: it opens no scope, so there is no boundary to sample at. Such a
35//! pass gets no query pair and **no row in the report**, rather than a row
36//! reading 0.000 ms that a reader would take for a measurement.
37//!
38//! # How many passes a ring slot holds
39//!
40//! Each slot is sized once, at [`PassTimers::new`], because a query set cannot
41//! grow and resizing one mid-frame would throw away the very submissions the
42//! ring is waiting on. So the capacity is a number the caller has to know before
43//! the first frame — and it is a fact about the renderers, not about the game.
44//! Each renderer carries a `MAX_PASSES`, [`UiRenderer::MAX_PASSES`] among them,
45//! and a caller passes the sum for the renderers its frame runs:
46//! `crcbl_render::MAX_TIMED_PASSES` is that sum for the engine's, and a frame
47//! that draws only a UI passes the UI pass's alone, plus any passes of its own.
48//!
49//! [`UiRenderer::MAX_PASSES`]: crate::ui_pass::UiRenderer::MAX_PASSES
50//!
51//! A frame with more passes than the capacity is timed as far as the capacity
52//! goes and the rest are dropped, with one warning. One, not one per frame: the
53//! condition holds for every frame once it holds for any, and this is a
54//! profiler.
55//!
56//! # Degrading, not breaking
57//!
58//! A device without [`Features::TIMESTAMP_QUERY`] cannot create a timestamp set.
59//! [`PassTimers::new`] reports that as `None`, the graph runs with no timers at
60//! all, and the report is empty. The seam says the same thing about
61//! [`PassTimestampWrites`] — accepted and dropped — because topic 10's browsers
62//! are where this actually happens.
63
64use core::fmt::Write as _;
65
66use crcbl_hal::{
67    CommandEncoder, Device, Features, PassTimestampWrites, QueryKind, QuerySetDesc, QuerySetHandle,
68};
69use crcbl_ui::debug::{DebugModule, DebugSection};
70
71use crate::graph::{CompiledPass, PassKind};
72
73/// What one pass cost on the GPU.
74#[derive(Clone, Debug, PartialEq, Eq)]
75pub struct PassTiming {
76    /// The pass's label, as it appears in the graph dump and in captures.
77    pub label: String,
78    /// Nanoseconds between pass boundaries, including inter-stage scheduling
79    /// gaps. These intervals can overlap on a pipelined GPU.
80    pub gpu_nanos: u64,
81}
82
83/// A whole frame's per-pass costs.
84#[derive(Clone, Debug, Default, PartialEq, Eq)]
85pub struct FrameTimings {
86    /// One entry per pass, in execution order.
87    pub passes: Vec<PassTiming>,
88    /// Which frame these came from — a few frames behind the one being
89    /// recorded; see the module docs.
90    pub frame: u64,
91    /// Elapsed interval from the earliest measured pass start to the latest
92    /// measured pass end. Includes gaps/contention, but not untimed work before
93    /// or after those boundaries. `None` means the timestamps were incomplete
94    /// or invalid; it must not be replaced with a sum of overlapping spans.
95    pub elapsed_nanos: Option<u64>,
96}
97
98impl FrameTimings {
99    /// The sum of every pass's elapsed span.
100    ///
101    /// This double-counts overlapping stages and includes scheduling gaps.
102    /// It is neither frame duration nor active GPU time. See `elapsed_nanos`
103    /// for the outer measured interval.
104    #[must_use]
105    pub fn total_nanos(&self) -> u64 {
106        self.passes.iter().map(|pass| pass.gpu_nanos).sum()
107    }
108
109    /// Whether anything was measured at all.
110    #[must_use]
111    pub fn is_empty(&self) -> bool {
112        self.passes.is_empty()
113    }
114
115    /// The report, as text.
116    ///
117    /// The other half of the graph's "explain itself" obligation: the dump says
118    /// what the frame *is* and this says what it *cost*.
119    #[must_use]
120    pub fn report(&self) -> String {
121        if self.passes.is_empty() {
122            return "frame timing: no GPU timestamps (the device has none)\n".to_string();
123        }
124        let mut out = String::new();
125        let total = self.total_nanos();
126        let _ = writeln!(
127            out,
128            "frame timing (frame {}): {} pass(es), {:.3} ms sum of pass spans",
129            self.frame,
130            self.passes.len(),
131            total as f64 / 1.0e6
132        );
133        if let Some(elapsed) = self.elapsed_nanos {
134            let _ = writeln!(
135                out,
136                "  measured GPU elapsed: {:.3} ms",
137                elapsed as f64 / 1.0e6
138            );
139        }
140        for pass in &self.passes {
141            let share = if total == 0 {
142                0.0
143            } else {
144                pass.gpu_nanos as f64 * 100.0 / total as f64
145            };
146            let _ = writeln!(
147                out,
148                "  {:<24} {:>9.3} ms  {:>5.1}%",
149                pass.label,
150                pass.gpu_nanos as f64 / 1.0e6,
151                share
152            );
153        }
154        out
155    }
156}
157
158/// The renderer's contribution to the debug overlay.
159///
160/// The UI plan's first profiler surface (debug item 1 in `docs/notes/tooling.md`) was "stage 2/3 GPU pass
161/// timestamps"; this is the adapter that puts them there. It lives here, not in
162/// `crcbl-ui`, because the overlay is not allowed to know that a render pass
163/// exists — the module is contributed by the system it reports on. `crcbl-render`
164/// already depends on `crcbl-ui` (it owns the UI pass), so this is the direction
165/// the dependency already runs.
166///
167/// Every row is a number [`PassTimers`] resolved from a timestamp query. No row
168/// is derived from anything else, and there is no CPU number here: this struct
169/// measures the GPU and says so.
170impl DebugModule for FrameTimings {
171    fn debug_section(&self, out: &mut DebugSection) {
172        out.set_title("gpu");
173        if self.passes.is_empty() {
174            // Reached when the device has timers but the ring has not come round
175            // yet — the report is deliberately frames latent. A device with no
176            // timestamps at all has no `PassTimers`, so the caller adds no
177            // section.
178            out.row_str("timings", "pending");
179            return;
180        }
181        for pass in &self.passes {
182            out.row(
183                &pass.label,
184                format_args!("{:.3} ms", pass.gpu_nanos as f64 / 1.0e6),
185            );
186        }
187        out.row(
188            "span sum",
189            format_args!("{:.3} ms", self.total_nanos() as f64 / 1.0e6),
190        );
191        if let Some(elapsed) = self.elapsed_nanos {
192            out.row("elapsed", format_args!("{:.3} ms", elapsed as f64 / 1.0e6));
193        }
194        out.row("frame", format_args!("{}", self.frame));
195    }
196}
197
198#[derive(Debug)]
199struct Slot {
200    set: QuerySetHandle,
201    /// The labels recorded into this slot, or empty if it has never been used.
202    labels: Vec<String>,
203    /// Which frame number was recorded into it.
204    frame: u64,
205}
206
207/// A ring of timestamp query sets, one per frame in flight plus one.
208#[derive(Debug)]
209pub struct PassTimers {
210    slots: Vec<Slot>,
211    current: usize,
212    /// Which query pair each pass of the frame being recorded was given, indexed
213    /// by its position in the frame. `None` for a pass that is not timed. Built
214    /// by [`PassTimers::begin_frame`] and read by
215    /// [`PassTimers::pass_writes`] as the graph walks the same list.
216    pairs: Vec<Option<u32>>,
217    capacity: u32,
218    frames: u64,
219    latest: FrameTimings,
220    /// Whether a frame with more passes than [`PassTimers::capacity`] has
221    /// already been reported. The condition holds for every frame once it holds
222    /// for one, and a line per frame forever is a line nobody reads.
223    warned: bool,
224}
225
226impl PassTimers {
227    /// Creates timers for up to `max_passes` passes across `frames_in_flight`
228    /// frames, or `None` if the device has no timestamp queries.
229    ///
230    /// `max_passes` is the sum of the `MAX_PASSES` of the renderers the frame
231    /// runs, plus the caller's own passes — see the module docs. A frame longer than it is timed as far as it goes.
232    ///
233    /// `None` is not an error: the seam is explicit that timestamps degrade
234    /// rather than break, and the caller's answer is to pass `None` to
235    /// [`CompiledGraph::execute`](crate::graph::CompiledGraph::execute) and get
236    /// an empty report.
237    #[must_use]
238    pub fn new(device: &dyn Device, frames_in_flight: usize, max_passes: u32) -> Option<Self> {
239        if !device.caps().features.contains(Features::TIMESTAMP_QUERY) {
240            crcbl_core::log::debug!(
241                "graph: no TIMESTAMP_QUERY on this device; per-pass timing is off"
242            );
243            return None;
244        }
245        // Two queries per pass, and the query index is a `u32` — so a capacity
246        // above half the range would overflow every `capacity * 2` below and
247        // reset a range shorter than the one it wrote.
248        let Some(query_count) = max_passes.checked_mul(2) else {
249            crcbl_core::log::debug!(
250                "graph: {max_passes} passes needs {} timestamp queries, more than a u32 index \
251                 holds; per-pass timing is off",
252                u64::from(max_passes) * 2
253            );
254            return None;
255        };
256        // One more than the frames in flight, so the slot about to be reused is
257        // always one whose submission has completed.
258        let count = frames_in_flight + 1;
259        let mut slots = Vec::with_capacity(count);
260        for index in 0..count {
261            match device.create_query_set(&QuerySetDesc {
262                label: Some("graph pass timers"),
263                kind: QueryKind::Timestamp,
264                // Two per pass: one before its barriers, one after it closes.
265                count: query_count,
266            }) {
267                Ok(set) => slots.push(Slot {
268                    set,
269                    labels: Vec::new(),
270                    frame: 0,
271                }),
272                Err(error) => {
273                    crcbl_core::log::debug!(
274                        "graph: timestamp set {index} refused ({error}); timing is off"
275                    );
276                    for slot in &slots {
277                        device.destroy_query_set(slot.set);
278                    }
279                    return None;
280                }
281            }
282        }
283        Some(Self {
284            slots,
285            current: 0,
286            pairs: Vec::new(),
287            capacity: max_passes,
288            frames: 0,
289            latest: FrameTimings::default(),
290            warned: false,
291        })
292    }
293
294    /// The most recent frame whose timestamps have actually landed.
295    ///
296    /// Empty until the ring has come round once.
297    #[must_use]
298    pub fn latest(&self) -> &FrameTimings {
299        &self.latest
300    }
301
302    /// How many passes these timers can bracket.
303    #[must_use]
304    pub const fn capacity(&self) -> u32 {
305        self.capacity
306    }
307
308    /// Starts a frame: resolves the slot about to be reused, then resets it.
309    ///
310    /// Called by the graph; a caller never has to.
311    pub(crate) fn begin_frame(
312        &mut self,
313        device: &dyn Device,
314        encoder: &mut dyn CommandEncoder,
315        passes: &[CompiledPass<'_>],
316    ) {
317        self.frames += 1;
318        self.current = (self.current + 1) % self.slots.len();
319
320        // The slot has come round: whatever was recorded into it belongs to a
321        // frame that has completed, so reading it neither stalls nor lies.
322        self.resolve(device);
323
324        // A copy pass opens no scope, so it has no boundary a backend could
325        // sample at and gets no query pair. Everything below counts *timed*
326        // passes for that reason, including the warning.
327        let timeable = passes
328            .iter()
329            .filter(|pass| pass.kind() != PassKind::Copy)
330            .count();
331        let used = timeable.min(self.capacity as usize);
332        if timeable > used && !self.warned {
333            self.warned = true;
334            crcbl_core::log::warn!(
335                "graph: {timeable} timed passes but timers hold {}; the last {} are untimed (said \
336                 once)",
337                self.capacity,
338                timeable - used
339            );
340        }
341        let slot = &mut self.slots[self.current];
342        slot.labels.clear();
343        self.pairs.clear();
344        for pass in passes {
345            let pair = if pass.kind() == PassKind::Copy {
346                None
347            } else {
348                let next = u32::try_from(slot.labels.len()).unwrap_or(u32::MAX);
349                (next < self.capacity).then(|| {
350                    slot.labels.push(pass.label().to_string());
351                    next
352                })
353            };
354            self.pairs.push(pair);
355        }
356        slot.frame = self.frames;
357        // Vulkan requires a reset before every write; the seam makes callers
358        // always do it so the Vulkan path is never the special case.
359        encoder.reset_query_set(slot.set, 0..self.capacity.saturating_mul(2));
360    }
361
362    /// The two queries pass `index` of this frame is bracketed by, or `None`
363    /// when it is not timed — a copy pass, or one past the ring's capacity.
364    ///
365    /// **What the graph puts in the pass descriptor.** There is no call to
366    /// record: the backend takes both samples where the pass opens and closes.
367    pub(crate) fn pass_writes(&self, index: usize) -> Option<PassTimestampWrites> {
368        let pair = *self.pairs.get(index)?;
369        pair.map(|pair| PassTimestampWrites {
370            set: self.slots[self.current].set,
371            beginning_of_pass: pair * 2,
372            end_of_pass: pair * 2 + 1,
373        })
374    }
375
376    fn resolve(&mut self, device: &dyn Device) {
377        let slot = &self.slots[self.current];
378        if slot.labels.is_empty() {
379            return;
380        }
381        // Nanoseconds, not ticks: `Device::query_results` converts inside the
382        // backend, where the scale is something the API actually reports.
383        let mut nanos = vec![0u64; slot.labels.len() * 2];
384        if let Err(error) = device.query_results(slot.set, 0, &mut nanos) {
385            crcbl_core::log::debug!(
386                "graph: timestamp read failed ({error}); dropping this frame's timing"
387            );
388            return;
389        }
390        let passes = slot
391            .labels
392            .iter()
393            .enumerate()
394            .map(|(index, label)| {
395                // `saturating_sub` rather than an assert: a device whose
396                // timestamps are unsupported writes zeros, and a zero-length
397                // pass is a more useful report than a panic in a profiler.
398                PassTiming {
399                    label: label.clone(),
400                    gpu_nanos: nanos[index * 2 + 1].saturating_sub(nanos[index * 2]),
401                }
402            })
403            .collect();
404        self.latest = FrameTimings {
405            passes,
406            frame: slot.frame,
407            elapsed_nanos: measured_span(&nanos),
408        };
409    }
410
411    /// Releases the query sets. Call after the device is idle.
412    pub fn destroy(&mut self, device: &dyn Device) {
413        for slot in &self.slots {
414            device.destroy_query_set(slot.set);
415        }
416        self.slots.clear();
417    }
418}
419
420/// Reject incomplete pairs rather than manufacturing a plausible budget value.
421fn measured_span(nanos: &[u64]) -> Option<u64> {
422    if nanos.is_empty() || !nanos.len().is_multiple_of(2) {
423        return None;
424    }
425    let mut first = u64::MAX;
426    let mut last = 0;
427    for pair in nanos.as_chunks::<2>().0 {
428        let (start, end) = (pair[0], pair[1]);
429        if start == 0 || end < start {
430            return None;
431        }
432        first = first.min(start);
433        last = last.max(end);
434    }
435    Some(last - first)
436}
437
438// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
439#[cfg(all(test, not(target_arch = "wasm32")))]
440mod tests {
441    use super::*;
442
443    #[test]
444    fn overlapping_passes_measure_the_outer_interval_not_their_sum() {
445        assert_eq!(measured_span(&[100, 500, 200, 900]), Some(800));
446        assert_eq!(measured_span(&[100, 200, 400, 700]), Some(600));
447        assert_eq!(measured_span(&[500, 500]), Some(0));
448    }
449
450    #[test]
451    fn a_missing_or_backwards_timestamp_cannot_supply_a_budget() {
452        for values in [
453            &[][..],
454            &[100][..],
455            &[0, 200][..],
456            &[100, 0][..],
457            &[200, 100][..],
458        ] {
459            assert_eq!(measured_span(values), None);
460        }
461        assert_eq!(measured_span(&[100, 200, 0, 400]), None);
462    }
463
464    #[test]
465    fn an_empty_report_says_so_rather_than_printing_nothing() {
466        let timings = FrameTimings::default();
467        assert!(timings.is_empty());
468        assert_eq!(timings.total_nanos(), 0);
469        assert!(timings.report().contains("no GPU timestamps"));
470    }
471
472    #[test]
473    fn the_report_lists_every_pass_with_its_share() {
474        let timings = FrameTimings {
475            elapsed_nanos: None,
476            frame: 42,
477            passes: vec![
478                PassTiming {
479                    label: "forward".to_string(),
480                    gpu_nanos: 3_000_000,
481                },
482                PassTiming {
483                    label: "tonemap".to_string(),
484                    gpu_nanos: 1_000_000,
485                },
486            ],
487        };
488        assert_eq!(timings.total_nanos(), 4_000_000);
489        let report = timings.report();
490        assert!(report.contains("frame 42"), "{report}");
491        assert!(report.contains("forward"), "{report}");
492        assert!(report.contains("tonemap"), "{report}");
493        assert!(report.contains("4.000 ms"), "{report}");
494        assert!(
495            report.contains("75.0%"),
496            "the shares must be there: {report}"
497        );
498        assert!(report.contains("25.0%"), "{report}");
499    }
500
501    /// A frame in which every pass measured zero must not divide by zero.
502    #[test]
503    fn a_zero_length_frame_reports_zero_shares_rather_than_nan() {
504        let timings = FrameTimings {
505            elapsed_nanos: None,
506            frame: 1,
507            passes: vec![PassTiming {
508                label: "clear".to_string(),
509                gpu_nanos: 0,
510            }],
511        };
512        let report = timings.report();
513        assert!(!report.contains("NaN"), "{report}");
514        assert!(report.contains("0.0%"), "{report}");
515    }
516
517    /// **The numbers on the overlay are the renderer's own.** Every pass the
518    /// timers resolved appears as a row, with the label the graph gave it and
519    /// the milliseconds its own nanoseconds convert to — and the whole thing
520    /// reaches the draw list, not just the section.
521    #[test]
522    fn the_debug_section_carries_the_passes_the_renderer_reported() {
523        use crcbl_ui::debug::{DebugOverlay, DebugRow};
524        use crcbl_ui::draw_list::{DrawCommand, DrawList};
525        use crcbl_ui::text::FontAtlas;
526        use glam::Vec2;
527
528        let timings = FrameTimings {
529            elapsed_nanos: None,
530            frame: 7,
531            passes: vec![
532                PassTiming {
533                    label: "sprites".to_string(),
534                    gpu_nanos: 2_500_000,
535                },
536                PassTiming {
537                    label: "ui".to_string(),
538                    gpu_nanos: 250_000,
539                },
540            ],
541        };
542
543        let mut section = DebugSection::default();
544        timings.debug_section(&mut section);
545        assert_eq!(section.title(), "gpu");
546        let rows: Vec<(&str, &str)> = section
547            .rows()
548            .iter()
549            .map(|DebugRow { label, value }| (label.as_str(), value.as_str()))
550            .collect();
551        assert_eq!(
552            rows,
553            [
554                ("sprites", "2.500 ms"),
555                ("ui", "0.250 ms"),
556                ("span sum", "2.750 ms"),
557                ("frame", "7"),
558            ],
559        );
560
561        // And through the panel: the same strings land in the draw list under
562        // the frame section, in the order the modules were added.
563        let mut overlay = DebugOverlay::with_visible(true);
564        overlay.record(core::time::Duration::from_millis(16));
565        overlay.begin_frame();
566        overlay.add(&timings);
567        let mut dl = DrawList::new();
568        overlay.render(&mut dl, Vec2::new(1280.0, 720.0), &FontAtlas::built_in());
569
570        let drawn: Vec<&str> = dl
571            .commands()
572            .iter()
573            .filter_map(|command| match command {
574                DrawCommand::Text { text, .. } => Some(text.as_str()),
575                _ => None,
576            })
577            .collect();
578        assert_eq!(drawn.first(), Some(&"frame"), "{drawn:?}");
579        let gpu = drawn
580            .iter()
581            .position(|text| *text == "gpu")
582            .expect("the gpu section is drawn");
583        assert_eq!(
584            &drawn[gpu..],
585            [
586                "gpu", "sprites", "2.500 ms", "ui", "0.250 ms", "span sum", "2.750 ms", "frame",
587                "7",
588            ],
589        );
590    }
591
592    /// A device that has timers but has not resolved a frame yet says so rather
593    /// than reporting a 0.000 ms frame that never ran.
594    #[test]
595    fn a_latent_report_renders_as_pending_rather_than_zero() {
596        let mut section = DebugSection::default();
597        FrameTimings::default().debug_section(&mut section);
598        assert_eq!(section.title(), "gpu");
599        assert_eq!(section.rows().len(), 1);
600        assert_eq!(section.rows()[0].value, "pending");
601    }
602
603    /// The device this runs against has no timestamp queries, so the whole
604    /// subsystem must decline rather than fail.
605    #[test]
606    fn a_device_without_timestamps_gets_no_timers_and_no_error() {
607        use crcbl_hal::null::NullInstance;
608        use crcbl_hal::{DeviceDesc, Instance};
609
610        let instance = NullInstance::portable();
611        let adapter = instance.adapters().remove(0);
612        let device = instance
613            .create_device(&DeviceDesc {
614                label: None,
615                adapter: adapter.id,
616                required_features: Features::empty(),
617                optional_features: Features::empty(),
618                compatible_surface: None,
619            })
620            .expect("the null backend always opens");
621        assert!(
622            !device.caps().features.contains(Features::TIMESTAMP_QUERY),
623            "this test is only meaningful against a device that has none"
624        );
625        assert!(
626            PassTimers::new(device.as_ref(), 2, 8).is_none(),
627            "timers must decline rather than fail"
628        );
629    }
630}