Skip to main content

cranpose_render_wgpu/frame_graph/
pass_timing.rs

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