katra_core/time.rs
1//! Time helpers.
2//!
3//! Traces use two clocks:
4//! * **monotonic** — nanoseconds relative to profiler start; deterministic
5//! across replays and comparable across runs on the same machine;
6//! * **wall** — absolute wall-clock nanoseconds; used to anchor epochs and
7//! to correlate with external logs.
8
9use std::time::{SystemTime, UNIX_EPOCH};
10
11/// Current wall-clock time in nanoseconds since the Unix epoch.
12pub fn wall_now_ns() -> u64 {
13 SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(0)
14}
15
16/// Monotonic time in nanoseconds (process-local, arbitrary origin).
17pub fn monotonic_now_ns() -> u64 {
18 use std::time::Instant;
19 // A process-wide anchor so multiple profilers in one process share an origin.
20 static ANCHOR: std::sync::OnceLock<(Instant, u64)> = std::sync::OnceLock::new();
21 let (anchor, wall_at_anchor) = ANCHOR.get_or_init(|| (Instant::now(), wall_now_ns()));
22 let since = anchor.elapsed().as_nanos() as u64;
23 wall_at_anchor.wrapping_add(since)
24}