Skip to main content

cranpose_render_wgpu/
pass_timing.rs

1use std::{
2    cell::{Cell, RefCell},
3    sync::{
4        Arc,
5        atomic::{AtomicU8, Ordering},
6    },
7};
8
9const QUERY_CAPACITY: u32 = 512;
10
11const READBACK_SLOTS: usize = 4;
12
13const SLOT_FREE: u8 = 0;
14const SLOT_PENDING: u8 = 1;
15const SLOT_MAPPED: u8 = 2;
16const SLOT_FAILED: u8 = 3;
17const SLOT_RECORDING: u8 = 4;
18const SLOT_READY: u8 = 5;
19const SLOT_RESOLVING: u8 = 6;
20
21const PRINT_CADENCE_FRAMES: u64 = 60;
22
23pub(crate) fn pass_timing_requested() -> bool {
24    cranpose_core::DIAGNOSTICS.gpu_pass_timing.flag()
25}
26
27/// One label's aggregate inside the current print window.
28#[derive(Clone, Debug, PartialEq)]
29pub struct GpuPassTimingEntry {
30    /// The label the passes were recorded under.
31    pub label: String,
32    /// GPU time the label's passes took in the window, in milliseconds.
33    pub total_ms: f64,
34    /// How many passes carried the label in the window.
35    pub passes: u64,
36}
37
38/// GPU time by pass label, aggregated since the last `[GPU-PASS]` print.
39/// Check the invalid and dropped counters before comparing workloads; rejected
40/// frames contribute neither time nor passes to this report.
41#[derive(Clone, Debug, Default, PartialEq)]
42pub struct GpuPassTimingReport {
43    /// Frames whose complete, valid timestamps have been read back into this window.
44    pub frames: u32,
45    /// Frames rejected because their timestamps were incomplete or invalid.
46    pub invalid_frames: u32,
47    /// Frames omitted because no query slot was free or a readback failed.
48    pub dropped_frames: u64,
49    /// Passes omitted because the frame exceeded the query budget.
50    pub dropped_passes: u64,
51    /// Total GPU span — earliest pass begin to latest pass end, summed over
52    /// the window's frames. Per-label times are stage-boundary occupancy
53    /// windows that overlap on pipelined GPUs and can sum past the frame;
54    /// this span is the frame-level wall number they cannot give.
55    pub span_ms: f64,
56    /// Entries sorted by descending GPU time.
57    pub entries: Vec<GpuPassTimingEntry>,
58}
59
60#[derive(Clone, Copy, Default)]
61struct LabelTotal {
62    nanoseconds: u64,
63    passes: u64,
64}
65
66struct ReadbackSlot {
67    query_set: wgpu::QuerySet,
68    buffer: wgpu::Buffer,
69    state: Arc<AtomicU8>,
70    passes: RefCell<Vec<(u16, u32)>>,
71    incomplete: Cell<bool>,
72    // The newest tick the slot's last frame read; None when its readback
73    // was dropped. A sample of the next frame at or below it was not taken:
74    // Metal leaves the sample of a stage that did not run as the last frame
75    // left it, and resets no query.
76    newest_tick: Cell<Option<u64>>,
77}
78
79pub(crate) struct PassTimer {
80    recording_slot: Cell<Option<usize>>,
81    resolve_buffer: wgpu::Buffer,
82    period_ns: f32,
83    cursor: Cell<u32>,
84    labels: RefCell<Vec<String>>,
85    totals: RefCell<Vec<LabelTotal>>,
86    slots: Vec<ReadbackSlot>,
87    frame_index: Cell<u64>,
88    frames_harvested: Cell<u32>,
89    invalid_frames: Cell<u32>,
90    span_nanoseconds: Cell<u64>,
91    dropped_passes: Cell<u64>,
92    dropped_frames: Cell<u64>,
93}
94
95impl PassTimer {
96    #[expect(clippy::print_stderr, reason = "explains why no timings come")]
97    pub(crate) fn for_device(device: &wgpu::Device, queue: &wgpu::Queue) -> Option<Self> {
98        if !device.features().contains(wgpu::Features::TIMESTAMP_QUERY) {
99            eprintln!(
100                "[GPU-PASS] CRANPOSE_GPU_PASS_TIMING is set but the adapter lacks TIMESTAMP_QUERY; passes will not be timed"
101            );
102            return None;
103        }
104        let buffer_size = u64::from(QUERY_CAPACITY) * u64::from(wgpu::QUERY_SIZE);
105        let resolve_buffer = device.create_buffer(&wgpu::BufferDescriptor {
106            label: Some("Pass Timing Resolve Buffer"),
107            size: buffer_size,
108            usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC,
109            mapped_at_creation: false,
110        });
111        let slots = (0..READBACK_SLOTS)
112            .map(|_| ReadbackSlot {
113                query_set: device.create_query_set(&wgpu::QuerySetDescriptor {
114                    label: Some("Pass Timing Query Set"),
115                    ty: wgpu::QueryType::Timestamp,
116                    count: QUERY_CAPACITY,
117                }),
118                buffer: device.create_buffer(&wgpu::BufferDescriptor {
119                    label: Some("Pass Timing Readback Buffer"),
120                    size: buffer_size,
121                    usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
122                    mapped_at_creation: false,
123                }),
124                state: Arc::new(AtomicU8::new(SLOT_FREE)),
125                passes: RefCell::new(Vec::new()),
126                incomplete: Cell::new(false),
127                newest_tick: Cell::new(Some(0)),
128            })
129            .collect();
130        Some(Self {
131            recording_slot: Cell::new(None),
132            resolve_buffer,
133            period_ns: queue.get_timestamp_period(),
134            cursor: Cell::new(0),
135            labels: RefCell::new(Vec::new()),
136            totals: RefCell::new(Vec::new()),
137            slots,
138            frame_index: Cell::new(0),
139            frames_harvested: Cell::new(0),
140            invalid_frames: Cell::new(0),
141            span_nanoseconds: Cell::new(0),
142            dropped_passes: Cell::new(0),
143            dropped_frames: Cell::new(0),
144        })
145    }
146
147    pub(crate) fn query_set(&self) -> &wgpu::QuerySet {
148        &self.slots[self
149            .recording_slot
150            .get()
151            .expect("timed pass has a query slot")]
152        .query_set
153    }
154
155    pub(crate) fn begin_pass(&self, label: &str) -> Option<(u32, u32)> {
156        let begin = self.cursor.get();
157        if begin == 0 {
158            let Some(slot_index) = self
159                .slots
160                .iter()
161                .position(|slot| slot.state.load(Ordering::Acquire) == SLOT_FREE)
162            else {
163                self.dropped_frames.set(self.dropped_frames.get() + 1);
164                self.cursor.set(QUERY_CAPACITY);
165                return None;
166            };
167            self.recording_slot.set(Some(slot_index));
168            self.slots[slot_index]
169                .state
170                .store(SLOT_RECORDING, Ordering::Release);
171            self.slots[slot_index].incomplete.set(false);
172        }
173        if begin + 2 > QUERY_CAPACITY {
174            if let Some(slot_index) = self.recording_slot.get() {
175                self.dropped_passes.set(self.dropped_passes.get() + 1);
176                self.slots[slot_index].incomplete.set(true);
177            }
178            return None;
179        }
180        self.cursor.set(begin + 2);
181        let label_id = self.intern(label);
182        self.slots[self
183            .recording_slot
184            .get()
185            .expect("timed pass has a query slot")]
186        .passes
187        .borrow_mut()
188        .push((label_id, begin));
189        Some((begin, begin + 1))
190    }
191
192    fn intern(&self, label: &str) -> u16 {
193        let mut labels = self.labels.borrow_mut();
194        if let Some(id) = labels.iter().position(|known| known == label) {
195            return id as u16;
196        }
197        labels.push(label.to_string());
198        self.totals.borrow_mut().push(LabelTotal::default());
199        (labels.len() - 1) as u16
200    }
201
202    pub(crate) fn harvest_completed(&self) {
203        for slot in &self.slots {
204            match slot.state.load(Ordering::Acquire) {
205                SLOT_MAPPED => {
206                    match slot.buffer.slice(..).get_mapped_range() {
207                        Ok(mapped) => self.harvest_frame(slot, &mapped),
208                        Err(error) => {
209                            log::debug!("pass timings could not be read: {error}");
210                            self.dropped_frames.set(self.dropped_frames.get() + 1);
211                            slot.newest_tick.set(None);
212                        }
213                    }
214                    slot.buffer.unmap();
215                    slot.passes.borrow_mut().clear();
216                    slot.state.store(SLOT_FREE, Ordering::Release);
217                }
218                SLOT_FAILED => {
219                    self.dropped_frames.set(self.dropped_frames.get() + 1);
220                    slot.newest_tick.set(None);
221                    slot.passes.borrow_mut().clear();
222                    slot.state.store(SLOT_FREE, Ordering::Release);
223                }
224                _ => {}
225            }
226        }
227    }
228
229    fn harvest_frame(&self, slot: &ReadbackSlot, mapped: &[u8]) {
230        let floor = slot.newest_tick.get();
231        let (span, rejected) = {
232            let passes = slot.passes.borrow();
233            let span = match floor {
234                Some(floor) if !slot.incomplete.get() => accumulate_frame(
235                    &mut self.totals.borrow_mut(),
236                    &passes,
237                    mapped,
238                    floor,
239                    self.period_ns,
240                ),
241                _ => None,
242            };
243            slot.newest_tick.set(newest_tick(&passes, mapped));
244            // The first rejected frame of a print window says why.
245            let first = self.invalid_frames.get() == 0;
246            let rejected = (span.is_none() && first && !slot.incomplete.get())
247                .then(|| rejected_ticks(&self.labels.borrow(), &passes, mapped));
248            (span, rejected)
249        };
250        let Some(span) = span else {
251            self.invalid_frames.set(self.invalid_frames.get() + 1);
252            if let Some(rejected) = rejected {
253                log::warn!(
254                    "[GPU-PASS] a frame's timestamps were rejected, the slot's last frame read up to {floor:?}: {rejected}"
255                );
256            }
257            return;
258        };
259        self.span_nanoseconds
260            .set(self.span_nanoseconds.get().saturating_add(span));
261        self.frames_harvested.set(self.frames_harvested.get() + 1);
262    }
263
264    pub(crate) fn frame_submitted(&self, queue: &wgpu::Queue) {
265        let Some(slot_index) = self.recording_slot.get() else {
266            return;
267        };
268        let slot = &self.slots[slot_index];
269        slot.state.store(SLOT_PENDING, Ordering::Release);
270        let state = Arc::clone(&slot.state);
271        queue.on_submitted_work_done(move || state.store(SLOT_READY, Ordering::Release));
272    }
273
274    pub(crate) fn has_completed_queries(&self) -> bool {
275        self.slots
276            .iter()
277            .any(|slot| slot.state.load(Ordering::Acquire) == SLOT_READY)
278    }
279
280    pub(crate) fn resolve_completed_queries(&self, encoder: &mut wgpu::CommandEncoder) {
281        for slot in &self.slots {
282            if slot.state.load(Ordering::Acquire) != SLOT_READY {
283                continue;
284            }
285            let used = slot
286                .passes
287                .borrow()
288                .last()
289                .expect("submitted timed passes")
290                .1
291                + 2;
292            encoder.resolve_query_set(&slot.query_set, 0..used, &self.resolve_buffer, 0);
293            encoder.copy_buffer_to_buffer(
294                &self.resolve_buffer,
295                0,
296                &slot.buffer,
297                0,
298                u64::from(used) * u64::from(wgpu::QUERY_SIZE),
299            );
300            slot.state.store(SLOT_RESOLVING, Ordering::Release);
301        }
302    }
303
304    pub(crate) fn map_resolved_queries(&self) {
305        for slot in &self.slots {
306            if slot.state.load(Ordering::Acquire) != SLOT_RESOLVING {
307                continue;
308            }
309            slot.state.store(SLOT_PENDING, Ordering::Release);
310            let state = Arc::clone(&slot.state);
311            slot.buffer
312                .slice(..)
313                .map_async(wgpu::MapMode::Read, move |result| {
314                    let outcome = if result.is_ok() {
315                        SLOT_MAPPED
316                    } else {
317                        SLOT_FAILED
318                    };
319                    state.store(outcome, Ordering::Release);
320                });
321        }
322    }
323
324    pub(crate) fn finish_frame(&self) {
325        if let Some(slot_index) = self.recording_slot.take() {
326            let slot = &self.slots[slot_index];
327            if slot.state.load(Ordering::Acquire) == SLOT_RECORDING {
328                slot.passes.borrow_mut().clear();
329                slot.state.store(SLOT_FREE, Ordering::Release);
330            }
331        }
332        self.cursor.set(0);
333        let frame = self.frame_index.get() + 1;
334        self.frame_index.set(frame);
335        if frame.is_multiple_of(PRINT_CADENCE_FRAMES) {
336            self.print_and_reset_window(frame);
337        }
338    }
339
340    pub(crate) fn report(&self) -> GpuPassTimingReport {
341        let labels = self.labels.borrow();
342        let totals = self.totals.borrow();
343        let mut entries: Vec<GpuPassTimingEntry> = labels
344            .iter()
345            .zip(totals.iter())
346            .filter(|(_, total)| total.passes > 0)
347            .map(|(label, total)| GpuPassTimingEntry {
348                label: label.clone(),
349                total_ms: total.nanoseconds as f64 / 1_000_000.0,
350                passes: total.passes,
351            })
352            .collect();
353        entries.sort_by(|a, b| b.total_ms.total_cmp(&a.total_ms));
354        GpuPassTimingReport {
355            frames: self.frames_harvested.get(),
356            invalid_frames: self.invalid_frames.get(),
357            dropped_frames: self.dropped_frames.get(),
358            dropped_passes: self.dropped_passes.get(),
359            span_ms: self.span_nanoseconds.get() as f64 / 1_000_000.0,
360            entries,
361        }
362    }
363
364    #[expect(clippy::print_stderr, reason = "pass timings print when requested")]
365    fn print_and_reset_window(&self, frame: u64) {
366        let report = self.report();
367        if report.frames > 0 || report.invalid_frames > 0 || report.dropped_frames > 0 {
368            let frames = f64::from(report.frames.max(1));
369            let total_ms: f64 = report.entries.iter().map(|entry| entry.total_ms).sum();
370            let mut line = format!(
371                "[GPU-PASS f#{frame}] frames={} span={:.2}ms/frame occupancy={:.2}ms/frame invalid_frames={}",
372                report.frames,
373                report.span_ms / frames,
374                total_ms / frames,
375                report.invalid_frames,
376            );
377            for entry in &report.entries {
378                line.push_str(&format!(
379                    " | {} {:.2}ms x{:.1}",
380                    entry.label,
381                    entry.total_ms / frames,
382                    entry.passes as f64 / frames,
383                ));
384            }
385            if self.dropped_passes.get() > 0 || self.dropped_frames.get() > 0 {
386                line.push_str(&format!(
387                    " | dropped: passes={} frames={}",
388                    self.dropped_passes.get(),
389                    self.dropped_frames.get(),
390                ));
391            }
392            eprintln!("{line}");
393        }
394        for total in self.totals.borrow_mut().iter_mut() {
395            *total = LabelTotal::default();
396        }
397        self.frames_harvested.set(0);
398        self.invalid_frames.set(0);
399        self.span_nanoseconds.set(0);
400        self.dropped_passes.set(0);
401        self.dropped_frames.set(0);
402    }
403}
404
405pub(crate) fn begin_timed_render_pass<'encoder>(
406    pass_timer: Option<&PassTimer>,
407    encoder: &'encoder mut wgpu::CommandEncoder,
408    descriptor: &wgpu::RenderPassDescriptor<'_>,
409) -> wgpu::RenderPass<'encoder> {
410    crate::frame_graph::note_render_pass(descriptor);
411    let timing = pass_timer.and_then(|timer| {
412        timer
413            .begin_pass(descriptor.label.unwrap_or("<unlabeled pass>"))
414            .map(|(begin, end)| (timer, begin, end))
415    });
416    let timestamp_writes = timing.map(|(timer, begin, end)| wgpu::RenderPassTimestampWrites {
417        query_set: timer.query_set(),
418        beginning_of_pass_write_index: Some(begin),
419        end_of_pass_write_index: Some(end),
420    });
421    encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
422        timestamp_writes,
423        ..descriptor.clone()
424    })
425}
426
427fn tick(mapped: &[u8], index: u32) -> Option<u64> {
428    let offset = index as usize * 8;
429    let bytes = mapped.get(offset..offset + 8)?;
430    Some(u64::from_le_bytes(bytes.try_into().expect("8-byte slice")))
431}
432
433// Each pass's label and raw ticks: u64::MAX is a sample the GPU failed to
434// take, and 0 or a tick at or below the slot's last frame one it never took.
435fn rejected_ticks(labels: &[String], passes: &[(u16, u32)], mapped: &[u8]) -> String {
436    passes
437        .iter()
438        .map(|&(label_id, begin_index)| {
439            format!(
440                "{} {:?}..{:?}",
441                labels
442                    .get(usize::from(label_id))
443                    .map_or("?", String::as_str),
444                tick(mapped, begin_index),
445                tick(mapped, begin_index + 1)
446            )
447        })
448        .collect::<Vec<_>>()
449        .join(", ")
450}
451
452// The newest tick the GPU took in a frame.
453fn newest_tick(passes: &[(u16, u32)], mapped: &[u8]) -> Option<u64> {
454    passes
455        .iter()
456        .flat_map(|&(_, begin_index)| [begin_index, begin_index + 1])
457        .filter_map(|index| tick(mapped, index))
458        .filter(|&value| value != u64::MAX)
459        .max()
460}
461
462// A frame's span, its passes' times added to `totals`; None when a sample
463// is missing, was not taken (at or below `floor`) or failed.
464fn accumulate_frame(
465    totals: &mut [LabelTotal],
466    passes: &[(u16, u32)],
467    mapped: &[u8],
468    floor: u64,
469    period_ns: f32,
470) -> Option<u64> {
471    let read_tick = |index: u32| -> Option<u64> {
472        tick(mapped, index).filter(|&value| value > floor && value != u64::MAX)
473    };
474    let mut first_begin = u64::MAX;
475    let mut last_end = 0u64;
476    for &(label_id, begin_index) in passes {
477        totals.get(usize::from(label_id))?;
478        let (begin, end) = (read_tick(begin_index)?, read_tick(begin_index + 1)?);
479        if end < begin {
480            return None;
481        }
482        first_begin = first_begin.min(begin);
483        last_end = last_end.max(end);
484    }
485    if passes.is_empty() {
486        return None;
487    }
488    for &(label_id, begin_index) in passes {
489        let total = &mut totals[usize::from(label_id)];
490        let begin = read_tick(begin_index).expect("validated timestamp");
491        let end = read_tick(begin_index + 1).expect("validated timestamp");
492        total.nanoseconds = total
493            .nanoseconds
494            .saturating_add(((end - begin) as f64 * f64::from(period_ns)) as u64);
495        total.passes += 1;
496    }
497    Some(((last_end - first_begin) as f64 * f64::from(period_ns)) as u64)
498}
499
500#[cfg(test)]
501#[path = "tests/pass_timing_tests.rs"]
502mod tests;