Skip to main content

oa/core/
time.rs

1//! Nanosecond-precision host timing.
2//!
3//! Port provenance: `oa/core/time.h`.
4//!
5//! Provides [`Timestamp`], [`Stopwatch`], [`ScopedTimer`], and [`Datetime`] as
6//! thin, zero-cost wrappers over [`std::time::Instant`] and
7//! [`std::time::SystemTime`]. No external crate is required.
8//!
9//! # Usage
10//!
11//! ```rust,ignore
12//! // Stopwatch
13//! let mut sw = oa::Stopwatch::new();
14//! sw.start();
15//! // ... work ...
16//! println!("elapsed: {:.3}ms", sw.elapsed_ms());
17//!
18//! // ScopedTimer
19//! let mut elapsed = 0.0_f64;
20//! {
21//!     let _t = oa::ScopedTimer::new(&mut elapsed);
22//!     // ... work ...
23//! } // writes elapsed seconds on drop
24//! ```
25
26use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
27
28// ─── Timestamp ───────────────────────────────────────────────────────────────
29
30/// Nanosecond-precision monotonic timestamp.
31///
32/// Internally stores nanoseconds elapsed since an arbitrary monotonic origin.
33/// Two `Timestamp` values from the same process can be subtracted; the result
34/// is meaningful as a [`Duration`]. Do not compare values across processes.
35#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
36pub struct Timestamp {
37	nanos: i64,
38}
39
40/// The process-global monotonic origin for [`Timestamp::now()`].
41fn origin() -> Instant {
42	use std::sync::OnceLock;
43	static ORIGIN: OnceLock<Instant> = OnceLock::new();
44	*ORIGIN.get_or_init(Instant::now)
45}
46
47impl Timestamp {
48	/// Capture the current monotonic time.
49	pub fn now() -> Self {
50		let elapsed = origin().elapsed();
51		Self {
52			nanos: elapsed.as_nanos().min(i64::MAX as u128) as i64,
53		}
54	}
55
56	/// Zero origin timestamp.
57	pub const fn zero() -> Self {
58		Self { nanos: 0 }
59	}
60
61	/// Construct from nanoseconds.
62	pub const fn new_from_nanos(n: i64) -> Self {
63		Self { nanos: n }
64	}
65
66	/// Construct from seconds (f64).
67	pub fn new_from_secs_f64(s: f64) -> Self {
68		Self {
69			nanos: (s * 1e9) as i64,
70		}
71	}
72
73	/// Nanoseconds since origin.
74	pub const fn as_nanos(self) -> i64 {
75		self.nanos
76	}
77
78	/// Elapsed time as seconds (f64).
79	pub fn to_secs(self) -> f64 {
80		self.nanos as f64 / 1e9
81	}
82
83	/// Elapsed time as milliseconds (f64).
84	pub fn to_ms(self) -> f64 {
85		self.nanos as f64 / 1e6
86	}
87
88	/// True when the stored value is positive (constructed by `now()` or explicit
89	/// positive nanos).
90	pub fn is_valid(self) -> bool {
91		self.nanos > 0
92	}
93}
94
95impl std::ops::Sub for Timestamp {
96	type Output = Timestamp;
97	fn sub(self, rhs: Self) -> Self {
98		Self {
99			nanos: self.nanos.saturating_sub(rhs.nanos),
100		}
101	}
102}
103
104impl std::ops::Add for Timestamp {
105	type Output = Timestamp;
106	fn add(self, rhs: Self) -> Self {
107		Self {
108			nanos: self.nanos.saturating_add(rhs.nanos),
109		}
110	}
111}
112
113impl std::ops::SubAssign for Timestamp {
114	fn sub_assign(&mut self, rhs: Self) {
115		self.nanos = self.nanos.saturating_sub(rhs.nanos);
116	}
117}
118
119impl std::ops::AddAssign for Timestamp {
120	fn add_assign(&mut self, rhs: Self) {
121		self.nanos = self.nanos.saturating_add(rhs.nanos);
122	}
123}
124
125// ─── Stopwatch ───────────────────────────────────────────────────────────────
126
127/// Accumulating stopwatch.
128///
129/// ```rust,ignore
130/// let mut sw = oa::Stopwatch::new();
131/// sw.start();
132/// // ... work ...
133/// sw.stop();
134/// println!("{:.3}ms", sw.elapsed_ms());
135/// ```
136pub struct Stopwatch {
137	start: Timestamp,
138	elapsed: Timestamp,
139	running: bool,
140}
141
142impl Default for Stopwatch {
143	fn default() -> Self {
144		Self::new()
145	}
146}
147
148impl Stopwatch {
149	/// Create a stopped stopwatch with zero elapsed time.
150	pub fn new() -> Self {
151		Self {
152			start: Timestamp::zero(),
153			elapsed: Timestamp::zero(),
154			running: false,
155		}
156	}
157
158	/// Start accumulating. No-op if already running.
159	pub fn start(&mut self) {
160		if !self.running {
161			self.start = Timestamp::now();
162			self.running = true;
163		}
164	}
165
166	/// Stop accumulating. No-op if already stopped.
167	pub fn stop(&mut self) {
168		if self.running {
169			self.elapsed += Timestamp::now() - self.start;
170			self.running = false;
171		}
172	}
173
174	/// Reset elapsed to zero and stop.
175	pub fn reset(&mut self) {
176		self.elapsed = Timestamp::zero();
177		self.running = false;
178	}
179
180	/// Reset and immediately start.
181	pub fn restart(&mut self) {
182		self.reset();
183		self.start();
184	}
185
186	/// Current elapsed duration (includes running segment if active).
187	pub fn elapsed(&self) -> Timestamp {
188		if self.running {
189			self.elapsed + (Timestamp::now() - self.start)
190		} else {
191			self.elapsed
192		}
193	}
194
195	/// Elapsed in seconds.
196	pub fn elapsed_sec(&self) -> f64 {
197		self.elapsed().to_secs()
198	}
199
200	/// Elapsed in milliseconds.
201	pub fn elapsed_ms(&self) -> f64 {
202		self.elapsed().to_ms()
203	}
204
205	/// True while the stopwatch is running.
206	pub fn is_running(&self) -> bool {
207		self.running
208	}
209}
210
211// ─── ScopedTimer ─────────────────────────────────────────────────────────────
212
213/// RAII scoped timer.
214///
215/// Borrows a `f64` and writes elapsed seconds on drop.
216///
217/// ```rust,ignore
218/// let mut elapsed = 0.0_f64;
219/// {
220///     let _t = oa::ScopedTimer::new(&mut elapsed);
221///     expensive_work();
222/// }
223/// println!("took {elapsed:.3}s");
224/// ```
225pub struct ScopedTimer<'a> {
226	output: &'a mut f64,
227	start: Timestamp,
228}
229
230impl<'a> ScopedTimer<'a> {
231	/// Create a scoped timer that writes to `output` on drop.
232	pub fn new(output: &'a mut f64) -> Self {
233		Self {
234			output,
235			start: Timestamp::now(),
236		}
237	}
238}
239
240impl Drop for ScopedTimer<'_> {
241	fn drop(&mut self) {
242		*self.output = (Timestamp::now() - self.start).to_secs();
243	}
244}
245
246// ─── Datetime ────────────────────────────────────────────────────────────────
247
248/// UTC human-readable date/time.
249///
250/// For log display and file naming only — never for consensus or deterministic
251/// math.
252#[derive(Clone, Copy, Debug, PartialEq, Eq)]
253pub struct Datetime {
254	unix_secs: i64,
255}
256
257impl Datetime {
258	/// Capture the current UTC time.
259	pub fn now() -> Self {
260		let secs = SystemTime::now()
261			.duration_since(UNIX_EPOCH)
262			.unwrap_or(Duration::ZERO)
263			.as_secs();
264		Self {
265			unix_secs: secs as i64,
266		}
267	}
268
269	/// Construct from Unix timestamp in seconds.
270	pub const fn new_from_unix_secs(secs: i64) -> Self {
271		Self { unix_secs: secs }
272	}
273
274	/// Unix timestamp in seconds.
275	pub const fn as_unix_secs(self) -> i64 {
276		self.unix_secs
277	}
278}
279
280impl std::fmt::Display for Datetime {
281	/// Format as `"YYYY-MM-DD HH:MM:SS"` (UTC).
282	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
283		let s = self.unix_secs.unsigned_abs();
284		let secs = s % 60;
285		let mins = (s / 60) % 60;
286		let hours = (s / 3600) % 24;
287		let days = s / 86400;
288		// Civil date from day count (proleptic Gregorian, unsigned).
289		let (y, m, d) = civil_from_days(days);
290		write!(f, "{y:04}-{m:02}-{d:02} {hours:02}:{mins:02}:{secs:02}")
291	}
292}
293
294/// Convert days since Unix epoch to (year, month, day).
295/// Implements the Gregorian calendar algorithm from H. F. Hinnant.
296fn civil_from_days(z: u64) -> (u32, u32, u32) {
297	let z = z as i64 + 719_468;
298	let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
299	let doe = (z - era * 146_097) as u32;
300	let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
301	let y = yoe as i64 + era * 400;
302	let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
303	let mp = (5 * doy + 2) / 153;
304	let d = doy - (153 * mp + 2) / 5 + 1;
305	let m = if mp < 10 { mp + 3 } else { mp - 9 };
306	let y = if m <= 2 { y + 1 } else { y };
307	(y as u32, m, d)
308}