Skip to main content

wde_renderer/passes/
render_graph_timings.rs

1//! Timings of the frames and of the passes of the render graph, shown by its debug view (see
2//! [`RenderGraphDebugView`](super::RenderGraphDebugView)).
3use std::{
4    collections::{HashMap, VecDeque},
5    time::{Duration, Instant}
6};
7
8use wde_wgpu::{
9    command_buffer::CommandBuffer,
10    instance::{PresentMode, RenderInstanceData},
11    timestamps::GpuTimestamps
12};
13
14use super::{DebugPassReport, RenderPassId};
15
16/// Most passes timed on the GPU in a frame.
17const MAX_GPU_PASSES: u32 = 128;
18
19/// Average, minimum and maximum of a duration over the last frames, in milliseconds.
20#[derive(Clone, Copy, Debug, Default, PartialEq)]
21pub struct DebugTiming {
22    pub avg: f32,
23    pub min: f32,
24    pub max: f32
25}
26
27/// Timings of the last frames, over the [`RenderGraphDebugView::timing_window`](super::RenderGraphDebugView).
28#[derive(Clone, Debug, Default)]
29pub struct DebugFrameTimings {
30    /// Interval between two presented frames.
31    pub frame: Option<DebugTiming>,
32    /// Render schedule of the render thread, swapchain waits included.
33    pub render: Option<DebugTiming>,
34    /// Render schedule, swapchain waits excluded. Approximate, as other systems may run during the waits.
35    pub render_busy: Option<DebugTiming>,
36    /// Time blocked acquiring and presenting the swapchain texture: waiting for the present mode and the GPU.
37    pub swapchain_wait: Option<DebugTiming>,
38    /// Recording of the render graph commands.
39    pub graph_cpu: Option<DebugTiming>,
40    /// Render graph on the GPU, from the start of its first pass to the end of its last.
41    pub graph_gpu: Option<DebugTiming>,
42    pub present_mode: Option<PresentMode>,
43    /// Whether the device writes timestamps. Without them, the GPU timings stay empty.
44    pub gpu_supported: bool,
45    /// Last frames, oldest first: the CPU time of each pass in their execution order, in ms.
46    pub cpu_history: VecDeque<Vec<(RenderPassId, f32)>>,
47    /// Same as the `cpu_history` for the GPU times, a few frames late.
48    pub gpu_history: VecDeque<Vec<(RenderPassId, f32)>>,
49    /// Intervals between the last presented frames, oldest first, in ms.
50    pub frame_history: VecDeque<f32>
51}
52
53fn ms(duration: Duration) -> f32 {
54    duration.as_secs_f32() * 1000.0
55}
56
57fn push_bounded<T>(values: &mut VecDeque<T>, value: T, len: usize) {
58    while values.len() >= len.max(1) {
59        values.pop_front();
60    }
61    values.push_back(value);
62}
63
64#[derive(Default)]
65struct TimingWindow(VecDeque<f32>);
66impl TimingWindow {
67    fn push(&mut self, duration: Duration, len: usize) {
68        push_bounded(&mut self.0, ms(duration), len);
69    }
70
71    fn summary(&self) -> Option<DebugTiming> {
72        if self.0.is_empty() {
73            return None;
74        }
75        let (sum, min, max) = self
76            .0
77            .iter()
78            .fold((0.0, f32::MAX, f32::MIN), |(s, lo, hi), v| {
79                (s + v, lo.min(*v), hi.max(*v))
80            });
81        Some(DebugTiming {
82            avg: sum / self.0.len() as f32,
83            min,
84            max
85        })
86    }
87}
88
89#[derive(Default)]
90struct PassTimings {
91    cpu: TimingWindow,
92    gpu: TimingWindow
93}
94
95/// Timings measured in the render world, while the debug view is enabled.
96#[derive(Default)]
97pub(super) struct Timings {
98    /// Number of frames the timings are computed over.
99    pub(super) window: usize,
100    /// `None` until created by the first frame, then `Some(None)` if the device has no timestamps.
101    gpu: Option<Option<GpuTimestamps<Vec<RenderPassId>>>>,
102    /// Passes timed on the GPU this frame, by two timestamps each.
103    gpu_passes: Vec<RenderPassId>,
104    pass_start: Option<(RenderPassId, Instant, bool)>,
105    frame_start: Option<Instant>,
106    graph_start: Option<Instant>,
107    swapchain_wait: Duration,
108    last_present: Option<Instant>,
109
110    frame: TimingWindow,
111    render: TimingWindow,
112    render_busy: TimingWindow,
113    swapchain_waits: TimingWindow,
114    graph_cpu: TimingWindow,
115    graph_gpu: TimingWindow,
116    passes: HashMap<RenderPassId, PassTimings>,
117    /// CPU times of the passes of this frame.
118    frame_cpu: Vec<(RenderPassId, f32)>,
119    cpu_history: VecDeque<Vec<(RenderPassId, f32)>>,
120    gpu_history: VecDeque<Vec<(RenderPassId, f32)>>
121}
122
123impl Timings {
124    pub(super) fn begin_frame(&mut self, instance: &RenderInstanceData) {
125        self.frame_start = Some(Instant::now());
126        self.swapchain_wait = Duration::ZERO;
127
128        let window = self.window;
129        let Some(gpu) = self
130            .gpu
131            .get_or_insert_with(|| {
132                GpuTimestamps::new(instance, "render-graph-timestamps", MAX_GPU_PASSES * 2)
133            })
134            .as_mut()
135        else {
136            return;
137        };
138        for (passes, timestamps) in gpu.collect(instance) {
139            let duration = |start: usize| {
140                Duration::from_nanos(timestamps[start + 1].saturating_sub(timestamps[start]))
141            };
142            let mut frame = Vec::with_capacity(passes.len());
143            for (i, id) in passes.iter().take(timestamps.len() / 2).enumerate() {
144                let duration = duration(2 * i);
145                self.passes
146                    .entry(*id)
147                    .or_default()
148                    .gpu
149                    .push(duration, window);
150                frame.push((*id, ms(duration)));
151            }
152            push_bounded(&mut self.gpu_history, frame, window);
153            if let (Some(first), Some(last)) = (timestamps.first(), timestamps.last()) {
154                self.graph_gpu
155                    .push(Duration::from_nanos(last.saturating_sub(*first)), window);
156            }
157        }
158    }
159
160    pub(super) fn add_swapchain_wait(&mut self, wait: Duration) {
161        self.swapchain_wait += wait;
162    }
163
164    pub(super) fn presented(&mut self, wait: Duration) {
165        self.swapchain_wait += wait;
166        let now = Instant::now();
167        if let Some(last) = self.last_present.replace(now) {
168            self.frame.push(now - last, self.window);
169        }
170    }
171
172    pub(super) fn end_frame(&mut self) {
173        let Some(start) = self.frame_start.take() else {
174            return;
175        };
176        let render = start.elapsed();
177        self.render.push(render, self.window);
178        self.render_busy
179            .push(render.saturating_sub(self.swapchain_wait), self.window);
180        self.swapchain_waits.push(self.swapchain_wait, self.window);
181    }
182
183    pub(super) fn begin_graph(&mut self) {
184        self.graph_start = Some(Instant::now());
185        self.gpu_passes.clear();
186        self.frame_cpu.clear();
187    }
188
189    pub(super) fn begin_pass(&mut self, command_buffer: &mut CommandBuffer, id: RenderPassId) {
190        let gpu = self
191            .gpu
192            .as_mut()
193            .and_then(Option::as_mut)
194            .and_then(|gpu| gpu.write(command_buffer))
195            .is_some();
196        self.pass_start = Some((id, Instant::now(), gpu));
197    }
198
199    pub(super) fn end_pass(&mut self, command_buffer: &mut CommandBuffer) {
200        let Some((id, start, gpu)) = self.pass_start.take() else {
201            return;
202        };
203        let window = self.window;
204        let elapsed = start.elapsed();
205        self.passes.entry(id).or_default().cpu.push(elapsed, window);
206        self.frame_cpu.push((id, ms(elapsed)));
207        if gpu && let Some(Some(timestamps)) = self.gpu.as_mut() {
208            timestamps.write(command_buffer);
209            self.gpu_passes.push(id);
210        }
211    }
212
213    pub(super) fn end_graph(
214        &mut self,
215        instance: &RenderInstanceData,
216        command_buffer: &mut CommandBuffer
217    ) {
218        if let Some(start) = self.graph_start.take() {
219            self.graph_cpu.push(start.elapsed(), self.window);
220        }
221        let frame = std::mem::take(&mut self.frame_cpu);
222        push_bounded(&mut self.cpu_history, frame, self.window);
223        if let Some(Some(gpu)) = self.gpu.as_mut() {
224            gpu.resolve(
225                instance,
226                command_buffer,
227                std::mem::take(&mut self.gpu_passes)
228            );
229        }
230    }
231
232    pub(super) fn submitted(&mut self) {
233        if let Some(Some(gpu)) = self.gpu.as_mut() {
234            gpu.map();
235        }
236    }
237
238    pub(super) fn fill_reports(&self, reports: &mut [DebugPassReport]) {
239        for report in reports {
240            if let Some(timings) = self.passes.get(&report.id) {
241                report.cpu_time = timings.cpu.summary();
242                report.gpu_time = timings.gpu.summary();
243            }
244        }
245    }
246
247    pub(super) fn summary(&self, present_mode: Option<PresentMode>) -> DebugFrameTimings {
248        DebugFrameTimings {
249            frame: self.frame.summary(),
250            render: self.render.summary(),
251            render_busy: self.render_busy.summary(),
252            swapchain_wait: self.swapchain_waits.summary(),
253            graph_cpu: self.graph_cpu.summary(),
254            graph_gpu: self.graph_gpu.summary(),
255            present_mode,
256            gpu_supported: matches!(self.gpu, Some(Some(_))),
257            cpu_history: self.cpu_history.clone(),
258            gpu_history: self.gpu_history.clone(),
259            frame_history: self.frame.0.clone()
260        }
261    }
262}