1use std::sync::Arc;
13
14use crate::{Error, Result, Timestamp};
15
16use super::{Device, Event, Runtime, TimestampPair};
17
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21pub enum TimerDomain {
22 #[default]
24 Auto,
25 Host,
27 Device,
29}
30
31pub 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 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 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 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 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 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 pub const fn elapsed_milliseconds(&self) -> f64 {
180 self.last_milliseconds
181 }
182
183 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 pub const fn domain(&self) -> TimerDomain {
193 self.domain
194 }
195
196 pub const fn is_host(&self) -> bool {
198 matches!(self.domain, TimerDomain::Host)
199 }
200
201 pub const fn is_device(&self) -> bool {
203 matches!(self.domain, TimerDomain::Device)
204 }
205
206 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 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 pub fn name(&self) -> &str {
231 &self.name
232 }
233
234 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;