Skip to main content

alpha2_render/
frame_gpu_time.rs

1//! GPU time of an export frame's graph and pack, sampled every eighth frame with timestamp
2//! queries.
3//!
4//! CPU timings show when work was recorded and submitted, not how long the GPU ran it. Three
5//! empty compute passes bracket the graph and the pack in the frame's encoder; their timestamps
6//! resolve into a ring of mappable buffers read on a later frame once mapped. Nothing waits on
7//! them, so sampling is effectively free.
8
9use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
10use std::sync::{Arc, Mutex};
11
12/// Every this many frames one is sampled.
13const SAMPLE_EVERY: u64 = 8;
14/// Ring size; a frame skips sampling when every slot's map is still pending.
15const RING: usize = 4;
16const RESOLVED_BYTES: u64 = 3 * 8;
17
18/// What the sampled frames of an export measured.
19#[derive(Clone, Copy, Debug, Default, PartialEq)]
20pub struct FrameGpuTimes {
21    /// Summed GPU time from graph start to graph end.
22    pub render_ms: f64,
23    /// Summed GPU time from graph end to pack end.
24    pub pack_ms: f64,
25    /// Frames whose timestamps were read.
26    pub sampled_frames: u64,
27    /// Frames whose three timestamps were equal, as on backends that do not advance the counter
28    /// across empty passes (Metal). Not counted in `sampled_frames`.
29    pub flat_frames: u64,
30    /// Frames drawn in a timed submission, sampled or not.
31    pub timed_frames: u64,
32    /// Sampled frames whose timestamps were not read yet; a later take counts them.
33    pub unread_frames: u64,
34}
35
36impl FrameGpuTimes {
37    /// The mean graph time of a sampled frame, when any was sampled.
38    #[must_use]
39    #[allow(clippy::cast_precision_loss, reason = "a frame count far below 2^52")]
40    pub fn render_ms_per_frame(&self) -> Option<f64> {
41        (self.sampled_frames > 0).then(|| self.render_ms / self.sampled_frames as f64)
42    }
43
44    /// The mean pack time of a sampled frame, when any was sampled.
45    #[must_use]
46    #[allow(clippy::cast_precision_loss, reason = "a frame count far below 2^52")]
47    pub fn pack_ms_per_frame(&self) -> Option<f64> {
48        (self.sampled_frames > 0).then(|| self.pack_ms / self.sampled_frames as f64)
49    }
50}
51
52#[derive(Debug)]
53struct Slot {
54    resolve: wgpu::Buffer,
55    readback: wgpu::Buffer,
56    pending: AtomicBool,
57    /// Map outcome set by the callback: [`MAP_WAITING`], [`MAP_DONE`] or [`MAP_FAILED`].
58    mapped: Arc<AtomicU8>,
59}
60
61const MAP_WAITING: u8 = 0;
62const MAP_DONE: u8 = 1;
63const MAP_FAILED: u8 = 2;
64
65#[derive(Debug)]
66pub(crate) struct FrameGpuTimer {
67    queries: wgpu::QuerySet,
68    slots: Vec<Slot>,
69    frames: AtomicU64,
70    timed_since_take: AtomicU64,
71    /// Nanoseconds per timestamp tick.
72    period: f32,
73    totals: Mutex<FrameGpuTimes>,
74}
75
76pub(crate) struct FrameSample<'a> {
77    timer: &'a FrameGpuTimer,
78    slot: usize,
79}
80
81impl FrameGpuTimer {
82    /// Requires `TIMESTAMP_QUERY` on `device`.
83    pub(crate) fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
84        let queries = device.create_query_set(&wgpu::QuerySetDescriptor {
85            label: Some("alpha2 frame GPU time"),
86            ty: wgpu::QueryType::Timestamp,
87            count: 3,
88        });
89        let slots = (0..RING)
90            .map(|_| Slot {
91                resolve: device.create_buffer(&wgpu::BufferDescriptor {
92                    label: Some("alpha2 frame GPU time resolve"),
93                    size: RESOLVED_BYTES,
94                    usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC,
95                    mapped_at_creation: false,
96                }),
97                readback: device.create_buffer(&wgpu::BufferDescriptor {
98                    label: Some("alpha2 frame GPU time readback"),
99                    size: RESOLVED_BYTES,
100                    usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
101                    mapped_at_creation: false,
102                }),
103                pending: AtomicBool::new(false),
104                mapped: Arc::new(AtomicU8::new(MAP_WAITING)),
105            })
106            .collect();
107        Self {
108            queries,
109            slots,
110            frames: AtomicU64::new(0),
111            timed_since_take: AtomicU64::new(0),
112            period: queue.get_timestamp_period(),
113            totals: Mutex::default(),
114        }
115    }
116
117    #[allow(
118        clippy::cast_precision_loss,
119        reason = "a frame's span in timestamp ticks, far below 2^52"
120    )]
121    fn collect(&self) {
122        let mut totals = self
123            .totals
124            .lock()
125            .unwrap_or_else(std::sync::PoisonError::into_inner);
126        for slot in &self.slots {
127            if !slot.pending.load(Ordering::Acquire) {
128                continue;
129            }
130            match slot.mapped.load(Ordering::Acquire) {
131                MAP_WAITING => continue,
132                // A failed map (device lost) frees the slot without a sample.
133                MAP_FAILED => {
134                    slot.mapped.store(MAP_WAITING, Ordering::Release);
135                    slot.pending.store(false, Ordering::Release);
136                    continue;
137                }
138                _ => {}
139            }
140            if let Ok(bytes) = slot.readback.slice(..).get_mapped_range() {
141                let tick = |at: usize| {
142                    let mut word = [0; 8];
143                    word.copy_from_slice(&bytes[at * 8..at * 8 + 8]);
144                    u64::from_le_bytes(word)
145                };
146                let (start, graph_end, pack_end) = (tick(0), tick(1), tick(2));
147                // A reset or wrapped counter gives out-of-order timestamps; drop the sample.
148                if start == pack_end {
149                    totals.flat_frames += 1;
150                } else if start <= graph_end && graph_end <= pack_end {
151                    let milliseconds =
152                        |ticks: u64| ticks as f64 * f64::from(self.period) / 1_000_000.0;
153                    totals.render_ms += milliseconds(graph_end - start);
154                    totals.pack_ms += milliseconds(pack_end - graph_end);
155                    totals.sampled_frames += 1;
156                }
157            }
158            slot.readback.unmap();
159            slot.mapped.store(MAP_WAITING, Ordering::Release);
160            slot.pending.store(false, Ordering::Release);
161        }
162    }
163
164    /// Returns a free slot for every eighth frame, or `None`.
165    pub(crate) fn begin(&self) -> Option<FrameSample<'_>> {
166        let frame = self.frames.fetch_add(1, Ordering::Relaxed);
167        self.timed_since_take.fetch_add(1, Ordering::Relaxed);
168        if !frame.is_multiple_of(SAMPLE_EVERY) {
169            return None;
170        }
171        self.collect();
172        let slot = self
173            .slots
174            .iter()
175            .position(|slot| !slot.pending.load(Ordering::Acquire))?;
176        Some(FrameSample { timer: self, slot })
177    }
178
179    /// Totals of frames sampled since the last take, from completed maps; then resets them.
180    pub(crate) fn take(&self) -> FrameGpuTimes {
181        self.collect();
182        let mut times = std::mem::take(
183            &mut *self
184                .totals
185                .lock()
186                .unwrap_or_else(std::sync::PoisonError::into_inner),
187        );
188        times.timed_frames = self.timed_since_take.swap(0, Ordering::Relaxed);
189        let unread = self
190            .slots
191            .iter()
192            .filter(|slot| slot.pending.load(Ordering::Acquire))
193            .count();
194        times.unread_frames = u64::try_from(unread).unwrap_or(u64::MAX);
195        times
196    }
197}
198
199impl FrameSample<'_> {
200    /// An empty compute pass writing timestamp `index`: at its end for the first, at its beginning
201    /// for the others.
202    fn mark(&self, encoder: &mut wgpu::CommandEncoder, index: u32) {
203        let writes = if index == 0 {
204            wgpu::ComputePassTimestampWrites {
205                query_set: &self.timer.queries,
206                beginning_of_pass_write_index: None,
207                end_of_pass_write_index: Some(index),
208            }
209        } else {
210            wgpu::ComputePassTimestampWrites {
211                query_set: &self.timer.queries,
212                beginning_of_pass_write_index: Some(index),
213                end_of_pass_write_index: None,
214            }
215        };
216        drop(encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
217            label: Some("alpha2 frame GPU time mark"),
218            timestamp_writes: Some(writes),
219        }));
220    }
221
222    pub(crate) fn graph_start(&self, encoder: &mut wgpu::CommandEncoder) {
223        self.mark(encoder, 0);
224    }
225
226    pub(crate) fn graph_end(&self, encoder: &mut wgpu::CommandEncoder) {
227        self.mark(encoder, 1);
228    }
229
230    /// Marks the end of the pack and resolves the three timestamps toward the slot.
231    pub(crate) fn pack_end(&self, encoder: &mut wgpu::CommandEncoder) {
232        self.mark(encoder, 2);
233        let slot = &self.timer.slots[self.slot];
234        encoder.resolve_query_set(&self.timer.queries, 0..3, &slot.resolve, 0);
235        encoder.copy_buffer_to_buffer(&slot.resolve, 0, &slot.readback, 0, RESOLVED_BYTES);
236    }
237
238    /// Maps the slot after the frame's submission, for a later frame to read.
239    pub(crate) fn submitted(self, gpu: &alpha2_gpu::GpuContext) {
240        let slot = &self.timer.slots[self.slot];
241        slot.pending.store(true, Ordering::Release);
242        let mapped = Arc::clone(&slot.mapped);
243        gpu.map_async(
244            &slot.readback.slice(..),
245            wgpu::MapMode::Read,
246            move |result| {
247                mapped.store(
248                    if result.is_ok() { MAP_DONE } else { MAP_FAILED },
249                    Ordering::Release,
250                );
251            },
252        );
253    }
254}