spatialrust_gpu/
profiling.rs1use spatialrust_core::{SpatialError, SpatialResult};
4
5use crate::WgpuRuntime;
6
7#[derive(Clone, Debug, PartialEq)]
9pub struct GpuStageTiming {
10 pub stage: &'static str,
12 pub elapsed_ns: f64,
14}
15
16#[derive(Clone, Debug, Default, PartialEq)]
18pub struct GpuTimingReport {
19 pub stages: Vec<GpuStageTiming>,
21 pub device_to_host_bytes: u64,
23}
24
25pub struct GpuStageProfiler {
33 #[cfg(any(not(target_arch = "wasm32"), feature = "gpu-image", feature = "gpu-aoso-staging"))]
34 runtime_identity: std::sync::Arc<()>,
35 queries: wgpu::QuerySet,
36 max_stages: u32,
37 stages: Vec<&'static str>,
38 failed: bool,
39}
40
41impl GpuStageProfiler {
42 pub fn new(runtime: &WgpuRuntime, max_stages: u32) -> SpatialResult<Self> {
44 if !runtime.timestamp_queries_enabled() {
45 return Err(invalid("GPU timestamp queries are not enabled on this runtime"));
46 }
47 if max_stages == 0 || max_stages > wgpu::QUERY_SET_MAX_QUERIES / 2 {
48 return Err(invalid("GPU profiling capacity must be in 1..=2048 stages"));
49 }
50 Ok(Self {
51 #[cfg(any(
52 not(target_arch = "wasm32"),
53 feature = "gpu-image",
54 feature = "gpu-aoso-staging"
55 ))]
56 runtime_identity: runtime.profiling_identity(),
57 queries: runtime.device().create_query_set(&wgpu::QuerySetDescriptor {
58 label: Some("spatialrust-stage-timestamps"),
59 ty: wgpu::QueryType::Timestamp,
60 count: max_stages * 2,
61 }),
62 max_stages,
63 stages: Vec::new(),
64 failed: false,
65 })
66 }
67
68 #[cfg(any(not(target_arch = "wasm32"), feature = "gpu-image", feature = "gpu-aoso-staging"))]
69 pub(crate) fn validate(&self, runtime: &WgpuRuntime, required: u32) -> SpatialResult<()> {
70 if !std::sync::Arc::ptr_eq(&self.runtime_identity, &runtime.profiling_identity()) {
73 return Err(invalid("GPU profiler belongs to a different runtime"));
74 }
75 if self.failed {
76 return Err(invalid("GPU profiler contains a failed recording"));
77 }
78 if required > self.max_stages - self.stages.len() as u32 {
79 return Err(invalid("GPU profiling capacity is insufficient for this operation"));
80 }
81 Ok(())
82 }
83
84 #[cfg(any(feature = "gpu-image", feature = "gpu-aoso-staging"))]
85 pub(crate) fn finish_recording<T>(&mut self, result: &SpatialResult<T>) {
86 self.failed |= result.is_err();
89 }
90
91 #[cfg(not(target_arch = "wasm32"))]
96 pub fn collect(self, runtime: &WgpuRuntime) -> SpatialResult<GpuTimingReport> {
97 self.validate(runtime, 0)?;
98 if self.stages.is_empty() {
99 return Ok(GpuTimingReport::default());
100 }
101 let count = self.stages.len() as u32 * 2;
102 let bytes = u64::from(count) * 8;
103 let resolve = runtime.device().create_buffer(&wgpu::BufferDescriptor {
104 label: Some("gpu-timestamp-resolve"),
105 size: bytes,
106 usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC,
107 mapped_at_creation: false,
108 });
109 let staging = runtime.device().create_buffer(&wgpu::BufferDescriptor {
110 label: Some("gpu-timestamp-readback"),
111 size: bytes,
112 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
113 mapped_at_creation: false,
114 });
115 let mut encoder =
116 runtime.device().create_command_encoder(&wgpu::CommandEncoderDescriptor {
117 label: Some("gpu-timestamp-collect"),
118 });
119 encoder.resolve_query_set(&self.queries, 0..count, &resolve, 0);
120 encoder.copy_buffer_to_buffer(&resolve, 0, &staging, 0, bytes);
121 runtime.queue().submit(Some(encoder.finish()));
122 let slice = staging.slice(..);
123 let (sender, receiver) = std::sync::mpsc::channel();
124 slice.map_async(wgpu::MapMode::Read, move |result| {
125 let _ = sender.send(result);
126 });
127 runtime.device().poll(wgpu::Maintain::Wait);
128 receiver
129 .recv()
130 .map_err(|_| invalid("GPU timestamp map callback was lost"))?
131 .map_err(|error| invalid(&format!("GPU timestamp map failed: {error}")))?;
132 let data = slice.get_mapped_range();
133 let period = f64::from(runtime.queue().get_timestamp_period());
134 let stages = self
135 .stages
136 .into_iter()
137 .zip(data.chunks_exact(16))
138 .map(|(stage, pair)| GpuStageTiming { stage, elapsed_ns: elapsed_ns(pair, period) })
139 .collect();
140 drop(data);
141 staging.unmap();
142 Ok(GpuTimingReport { stages, device_to_host_bytes: bytes })
143 }
144}
145
146pub(crate) fn timestamp_writes<'a>(
147 profiler: &'a mut Option<&mut GpuStageProfiler>,
148 stage: &'static str,
149) -> Option<wgpu::ComputePassTimestampWrites<'a>> {
150 let profiler = profiler.as_deref_mut()?;
151 if profiler.failed || profiler.stages.len() as u32 >= profiler.max_stages {
152 profiler.failed = true;
153 return None;
154 }
155 let index = profiler.stages.len() as u32 * 2;
156 profiler.stages.push(stage);
157 Some(wgpu::ComputePassTimestampWrites {
158 query_set: &profiler.queries,
159 beginning_of_pass_write_index: Some(index),
160 end_of_pass_write_index: Some(index + 1),
161 })
162}
163
164fn invalid(message: &str) -> SpatialError {
165 SpatialError::InvalidArgument(message.to_owned())
166}
167
168#[cfg(not(target_arch = "wasm32"))]
169fn elapsed_ns(pair: &[u8], period: f64) -> f64 {
170 let begin = u64::from_le_bytes(pair[..8].try_into().expect("timestamp width"));
171 let end = u64::from_le_bytes(pair[8..].try_into().expect("timestamp width"));
172 end.wrapping_sub(begin) as f64 * period
173}
174
175#[cfg(all(test, not(target_arch = "wasm32")))]
176mod tests {
177 #[test]
178 fn timestamp_ticks_convert_to_ns_including_zero_and_wraparound() {
179 for (begin, end, expected) in
180 [(100_u64, 160_u64, 30.0), (7, 7, 0.0), (u64::MAX - 3, 4, 4.0)]
181 {
182 let mut pair = Vec::from(begin.to_le_bytes());
183 pair.extend_from_slice(&end.to_le_bytes());
184 assert_eq!(super::elapsed_ns(&pair, 0.5), expected);
185 }
186 }
187}