Skip to main content

oa/runtime/
timer.rs

1//! Named host/device measurement regions.
2//!
3//! Donor: `oacpp/source/cpp/include/oa/runtime/timer.h`,
4//! `timer.cpp`, and `timerRegistry.{h,cpp}`.
5//! Adaptation: Rust naming (`Timer`, `TimerDomain`); each device timer owns one
6//! dedicated timestamp pair instead of a pooled registry slot — the donor's
7//! slot pooling is an internal allocation optimization with the same public
8//! contract. Device regions are recorded by
9//! [`Runtime::checkpoint_with_timer`]; [`Timer::commit`] never waits and
10//! requires the attached submission event to be complete.
11
12use std::sync::Arc;
13
14use crate::{Error, Result, Timestamp};
15
16use super::{Device, Event, Runtime, TimestampPair};
17
18/// Clock domain measured by one [`Timer`]. `Auto` resolves to `Device` on
19/// [`Timer::init`] and to `Host` on the first [`Timer::begin`].
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21pub enum TimerDomain {
22	/// Resolved by the first timing operation.
23	#[default]
24	Auto,
25	/// Host-side monotonic region bracketed by [`Timer::begin`]/[`Timer::end`].
26	Host,
27	/// Device-side region bracketed by one timer-tagged runtime submission.
28	Device,
29}
30
31/// One named measurement region.
32///
33/// A host timer brackets arbitrary host code. A device timer must be
34/// initialized against an runtime, then one
35/// [`Runtime::checkpoint_with_timer`] records the device timestamps around the
36/// submitted batch. The device path is single-flight: a timer cannot tag a
37/// new submission while its previous one is still pending.
38pub struct Timer {
39	domain: TimerDomain,
40	name: String,
41	host_start: Option<Timestamp>,
42	host_end: Option<Timestamp>,
43	host_running: bool,
44	host_complete: bool,
45	device_pair: Option<TimestampPair>,
46	device_event: Option<Event>,
47	last_milliseconds: f64,
48	last_units: f64,
49}
50
51impl Timer {
52	/// Create a timer in `domain` named `name`.
53	pub fn new(domain: TimerDomain, name: impl Into<String>) -> Self {
54		Self {
55			domain,
56			name: name.into(),
57			host_start: None,
58			host_end: None,
59			host_running: false,
60			host_complete: false,
61			device_pair: None,
62			device_event: None,
63			last_milliseconds: 0.0,
64			last_units: 1.0,
65		}
66	}
67
68	/// Resolve `Auto` to `Device` and acquire this runtime's device timestamp
69	/// backend. A host timer needs no runtime and initialization is a no-op.
70	///
71	/// # Errors
72	///
73	/// Returns an error when the domain is `Device` and the runtime's compute
74	/// queue cannot provide timestamps.
75	pub fn init(&mut self, runtime: &Runtime, name: impl Into<String>) -> Result<()> {
76		let name = name.into();
77		if !name.is_empty() {
78			self.name = name;
79		}
80		if self.domain == TimerDomain::Auto {
81			self.domain = TimerDomain::Device;
82		}
83		if self.domain == TimerDomain::Host {
84			return Ok(());
85		}
86		self.device_pair = Some(runtime.device_timestamp_pair()?);
87		self.device_event = None;
88		Ok(())
89	}
90
91	/// Begin a host-side region. `Auto` resolves to `Host` here.
92	///
93	/// # Errors
94	///
95	/// Returns an error when the timer resolves to `Device` — device regions are
96	/// recorded by [`Runtime::checkpoint_with_timer`] — or when a previous host
97	/// region is still running.
98	pub fn begin(&mut self) -> Result<()> {
99		if self.domain == TimerDomain::Auto {
100			self.domain = TimerDomain::Host;
101		}
102		if self.domain != TimerDomain::Host {
103			return Err(Error::failed_precondition(
104				"device timer regions are recorded by Runtime::checkpoint_with_timer",
105			));
106		}
107		if self.host_running {
108			return Err(Error::failed_precondition(
109				"host timer begin requires the previous region to end",
110			));
111		}
112		self.host_start = Some(Timestamp::now());
113		self.host_running = true;
114		self.host_complete = false;
115		Ok(())
116	}
117
118	/// End the running host-side region.
119	///
120	/// # Errors
121	///
122	/// Returns an error without a matching [`Timer::begin`].
123	pub fn end(&mut self) -> Result<()> {
124		if self.domain != TimerDomain::Host || !self.host_running {
125			return Err(Error::failed_precondition(
126				"host timer end requires a matching begin",
127			));
128		}
129		self.host_end = Some(Timestamp::now());
130		self.host_running = false;
131		self.host_complete = true;
132		Ok(())
133	}
134
135	/// Commit the measured region in milliseconds and remember `units` for
136	/// [`Timer::throughput`]. Never waits: a device timer requires its tagged
137	/// submission to be complete.
138	///
139	/// # Errors
140	///
141	/// - `FailedPrecondition`: no completed region exists (host timer without a
142	///   finished `begin`/`end`, device timer without a tagged submission).
143	/// - `NotReady`: the device submission is still pending.
144	/// - Vulkan timestamp readback failures.
145	pub fn commit(&mut self, units: f64) -> Result<f64> {
146		self.last_milliseconds = match self.domain {
147			TimerDomain::Device => {
148				let pair = self.device_pair.as_ref().ok_or_else(|| {
149					Error::failed_precondition("device timer commit requires init and a submitted region")
150				})?;
151				let event = self.device_event.as_ref().ok_or_else(|| {
152					Error::failed_precondition("device timer commit requires a submitted region")
153				})?;
154				if !event.is_complete()? {
155					return Err(Error::not_ready("device timer submission is still pending"));
156				}
157				pair.duration()?.as_secs_f64() * 1e3
158			}
159			TimerDomain::Host => {
160				if !self.host_complete {
161					return Err(Error::failed_precondition(
162						"host timer commit requires a completed begin/end region",
163					));
164				}
165				self.host_complete = false;
166				(self.host_end.expect("complete region has an end")
167					- self.host_start.expect("complete region has a start"))
168				.to_ms()
169			}
170			TimerDomain::Auto => {
171				return Err(Error::failed_precondition("timer has no measured region"));
172			}
173		};
174		self.last_units = units;
175		Ok(self.last_milliseconds)
176	}
177
178	/// Return the last committed region duration in milliseconds.
179	pub const fn elapsed_milliseconds(&self) -> f64 {
180		self.last_milliseconds
181	}
182
183	/// Return committed units per second, or `0.0` before a nonzero commit.
184	pub const fn throughput(&self) -> f64 {
185		if self.last_milliseconds <= 0.0 {
186			return 0.0;
187		}
188		self.last_units / (self.last_milliseconds / 1000.0)
189	}
190
191	/// Return the resolved or configured domain.
192	pub const fn domain(&self) -> TimerDomain {
193		self.domain
194	}
195
196	/// Return whether this timer measures host regions.
197	pub const fn is_host(&self) -> bool {
198		matches!(self.domain, TimerDomain::Host)
199	}
200
201	/// Return whether this timer measures device regions.
202	pub const fn is_device(&self) -> bool {
203		matches!(self.domain, TimerDomain::Device)
204	}
205
206	/// Return whether this timer can measure in its current domain. A host
207	/// timer is always initialized; a device timer requires [`Timer::init`].
208	pub fn is_initialized(&self) -> bool {
209		match self.domain {
210			TimerDomain::Host => true,
211			TimerDomain::Device => self.device_pair.is_some(),
212			TimerDomain::Auto => false,
213		}
214	}
215
216	/// Return whether a measurement region is in flight: a running host region,
217	/// or a device submission that has not completed.
218	pub fn is_pending(&self) -> bool {
219		match self.domain {
220			TimerDomain::Host => self.host_running,
221			TimerDomain::Device => self
222				.device_event
223				.as_ref()
224				.is_some_and(|event| !event.is_complete().unwrap_or(true)),
225			TimerDomain::Auto => false,
226		}
227	}
228
229	/// Return the configured timer name.
230	pub fn name(&self) -> &str {
231		&self.name
232	}
233
234	/// Validate a timer-tagged submission against this timer's device state.
235	pub(in crate::runtime) fn prepare_device_submit(&mut self, device: &Arc<Device>) -> Result<()> {
236		if self.domain != TimerDomain::Device {
237			return Err(Error::failed_precondition(
238				"runtime submission requires an initialized device timer",
239			));
240		}
241		let pair = self.device_pair.as_ref().ok_or_else(|| {
242			Error::failed_precondition("device timer requires init before timed submission")
243		})?;
244		if !pair.belongs_to(device) {
245			return Err(Error::invalid_argument(
246				"device timer was initialized by another runtime",
247			));
248		}
249		if self.is_pending() {
250			return Err(Error::failed_precondition(
251				"device timer is still pending; commit the previous region before resubmitting",
252			));
253		}
254		Ok(())
255	}
256
257	pub(in crate::runtime) fn device_pair(&self) -> Option<&TimestampPair> {
258		self.device_pair.as_ref()
259	}
260
261	pub(in crate::runtime) fn attach_event(&mut self, event: Event) {
262		self.device_event = Some(event);
263	}
264}
265
266#[cfg(test)]
267#[path = "../../../../test/rs/runtime/timer_unit.rs"]
268mod tests;