Skip to main content

pointblitz_core/
timer.rs

1//! GPU time of a run of frames from pass timestamps (decision 0049).
2//!
3//! [`GpuTimer::next`] points the renderer's next pass at a fresh begin/end pair, [`GpuTimer::resolve`]
4//! copies the timestamps to a mappable buffer at the end of the run, and after the caller has mapped
5//! [`GpuTimer::readback`], [`GpuTimer::take_ms`] sums the passes. Mapping is left to the caller so a
6//! native loop can block and a browser can await.
7
8use crate::Renderer;
9
10pub struct GpuTimer {
11    set: wgpu::QuerySet,
12    resolved: wgpu::Buffer,
13    readback: wgpu::Buffer,
14    /// Frames the set holds (two timestamps each).
15    capacity: u32,
16    /// Frames written since the last `take_ms`.
17    used: u32,
18    /// Nanoseconds per timestamp tick.
19    period_ns: f32,
20}
21
22impl GpuTimer {
23    /// `None` when the device was created without `Features::TIMESTAMP_QUERY`.
24    pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, frames: u32) -> Option<Self> {
25        if !device.features().contains(wgpu::Features::TIMESTAMP_QUERY) {
26            return None;
27        }
28        let capacity = frames.max(1);
29        let bytes = u64::from(capacity) * 2 * 8;
30        Some(Self {
31            set: device.create_query_set(&wgpu::QuerySetDescriptor {
32                label: Some("frame timestamps"),
33                ty: wgpu::QueryType::Timestamp,
34                count: capacity * 2,
35            }),
36            resolved: device.create_buffer(&wgpu::BufferDescriptor {
37                label: Some("frame timestamps resolved"),
38                size: bytes,
39                usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC,
40                mapped_at_creation: false,
41            }),
42            readback: device.create_buffer(&wgpu::BufferDescriptor {
43                label: Some("frame timestamps readback"),
44                size: bytes,
45                usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
46                mapped_at_creation: false,
47            }),
48            capacity,
49            used: 0,
50            period_ns: queue.get_timestamp_period(),
51        })
52    }
53
54    /// Times the renderer's next pass. Past the capacity the pass is not timed.
55    pub fn next(&mut self, renderer: &mut Renderer) {
56        if self.used < self.capacity {
57            renderer.set_timestamp_writes(Some((self.set.clone(), self.used * 2)));
58            self.used += 1;
59        } else {
60            renderer.set_timestamp_writes(None);
61        }
62    }
63
64    /// Stops timing and copies this run's timestamps to [`Self::readback`].
65    pub fn resolve(&mut self, renderer: &mut Renderer, encoder: &mut wgpu::CommandEncoder) {
66        renderer.set_timestamp_writes(None);
67        if self.used == 0 {
68            return;
69        }
70        encoder.resolve_query_set(&self.set, 0..self.used * 2, &self.resolved, 0);
71        encoder.copy_buffer_to_buffer(
72            &self.resolved,
73            0,
74            &self.readback,
75            0,
76            u64::from(self.used) * 16,
77        );
78    }
79
80    /// The buffer to map (read) after the resolve was submitted.
81    pub fn readback(&self) -> &wgpu::Buffer {
82        &self.readback
83    }
84
85    /// Sum of the timed passes in ms, read from the mapped [`Self::readback`], which it unmaps.
86    /// Returns the number of passes too.
87    pub fn take_ms(&mut self) -> (f64, u32) {
88        let n = self.used;
89        self.used = 0;
90        if n == 0 {
91            return (0.0, 0);
92        }
93        let ticks: u64 = {
94            let view = self
95                .readback
96                .get_mapped_range(..u64::from(n) * 16)
97                .expect("mapped");
98            view.as_chunks::<16>()
99                .0
100                .iter()
101                .map(|pair| {
102                    let (begin, end) = pair.split_at(8);
103                    let tick = |b: &[u8]| u64::from_le_bytes(b.try_into().expect("8 bytes"));
104                    tick(end).saturating_sub(tick(begin))
105                })
106                .sum()
107        };
108        self.readback.unmap();
109        (ticks as f64 * f64::from(self.period_ns) / 1e6, n)
110    }
111}