Skip to main content

qualia_core_db/platform/
precision_timer.rs

1//! Precision Timer and Sub-Millisecond Benchmark Telemetry.
2//!
3//! Solves the truncation problem where ultra-fast zero-heap graph traversals,
4//! SIMD matrix operations, and NQuin evaluations (150 ns – 40 µs) truncate
5//! to integer 0 ms when converted via `as_millis() as u64`.
6
7use std::time::{Duration, Instant};
8
9/// Formats a duration into a human-readable string with appropriate sub-millisecond units.
10pub fn format_duration_human(duration: Duration) -> String {
11    let nanos = duration.as_nanos();
12    if nanos < 1_000 {
13        format!("{nanos} ns")
14    } else if nanos < 1_000_000 {
15        format!("{:.3} µs", nanos as f64 / 1_000.0)
16    } else if nanos < 1_000_000_000 {
17        format!("{:.3} ms", nanos as f64 / 1_000_000.0)
18    } else {
19        format!("{:.3} s", duration.as_secs_f64())
20    }
21}
22
23/// Extension trait for `std::time::Duration` providing sub-millisecond precision helpers.
24pub trait DurationPrecisionExt {
25    /// Returns elapsed time in fractional microseconds (e.g. 12.345 µs).
26    fn as_micros_f64(&self) -> f64;
27    /// Returns elapsed time in fractional milliseconds (e.g. 0.042 ms instead of 0 ms).
28    fn as_millis_f64(&self) -> f64;
29    /// Returns a formatted human-readable string with automatic unit scaling (ns, µs, ms, s).
30    fn format_human(&self) -> String;
31}
32
33impl DurationPrecisionExt for Duration {
34    #[inline]
35    fn as_micros_f64(&self) -> f64 {
36        self.as_nanos() as f64 / 1_000.0
37    }
38
39    #[inline]
40    fn as_millis_f64(&self) -> f64 {
41        self.as_nanos() as f64 / 1_000_000.0
42    }
43
44    #[inline]
45    fn format_human(&self) -> String {
46        format_duration_human(*self)
47    }
48}
49
50/// High-resolution stopwatch for measuring sub-millisecond graph and computational operations.
51#[derive(Debug, Clone, Copy)]
52pub struct PrecisionTimer {
53    start_instant: Instant,
54}
55
56impl Default for PrecisionTimer {
57    fn default() -> Self {
58        Self::now()
59    }
60}
61
62impl PrecisionTimer {
63    /// Starts a new precision timer at the current instant.
64    #[inline]
65    pub fn now() -> Self {
66        Self {
67            start_instant: Instant::now(),
68        }
69    }
70
71    /// Resets the timer to the current instant and returns the elapsed duration.
72    #[inline]
73    pub fn restart(&mut self) -> Duration {
74        let elapsed = self.start_instant.elapsed();
75        self.start_instant = Instant::now();
76        elapsed
77    }
78
79    /// Returns elapsed duration.
80    #[inline]
81    pub fn elapsed(&self) -> Duration {
82        self.start_instant.elapsed()
83    }
84
85    /// Returns elapsed time in integer nanoseconds (10⁻⁹ seconds).
86    #[inline]
87    pub fn elapsed_nanos(&self) -> u64 {
88        self.start_instant.elapsed().as_nanos() as u64
89    }
90
91    /// Returns elapsed time in fractional microseconds (e.g. 1.250 µs).
92    #[inline]
93    pub fn elapsed_micros_f64(&self) -> f64 {
94        self.start_instant.elapsed().as_micros_f64()
95    }
96
97    /// Returns elapsed time in fractional milliseconds (e.g. 0.015 ms instead of 0).
98    #[inline]
99    pub fn elapsed_millis_f64(&self) -> f64 {
100        DurationPrecisionExt::as_millis_f64(&self.start_instant.elapsed())
101    }
102
103    /// Formats the elapsed time as a readable string (e.g. "340 ns", "12.45 µs").
104    #[inline]
105    pub fn format_elapsed(&self) -> String {
106        self.start_instant.elapsed().format_human()
107    }
108
109    /// Runs a closure over N iterations to measure throughput without zero-ms truncation.
110    pub fn benchmark_fn<F: FnMut()>(iterations: usize, mut f: F) -> BenchmarkResult {
111        let iterations = iterations.max(1);
112        let timer = Self::now();
113        for _ in 0..iterations {
114            f();
115        }
116        let total_duration = timer.elapsed();
117        let total_nanos = total_duration.as_nanos() as f64;
118        let nanos_per_op = total_nanos / (iterations as f64);
119        let ops_per_sec = (iterations as f64) / total_duration.as_secs_f64().max(1e-9);
120
121        BenchmarkResult {
122            iterations,
123            total_duration,
124            nanos_per_op,
125            ops_per_sec,
126        }
127    }
128}
129
130/// High-precision benchmark summary.
131#[derive(Debug, Clone, PartialEq)]
132pub struct BenchmarkResult {
133    pub iterations: usize,
134    pub total_duration: Duration,
135    pub nanos_per_op: f64,
136    pub ops_per_sec: f64,
137}
138
139impl BenchmarkResult {
140    /// Converts to `report_string`.
141    pub fn to_report_string(&self) -> String {
142        format!(
143            "Iterations: {} | Total: {} | Speed: {:.2} ns/op ({:.2} M-ops/s)",
144            self.iterations,
145            self.total_duration.format_human(),
146            self.nanos_per_op,
147            self.ops_per_sec / 1_000_000.0,
148        )
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    #[test]
157    fn test_format_duration_human() {
158        assert_eq!(format_duration_human(Duration::from_nanos(450)), "450 ns");
159        assert_eq!(format_duration_human(Duration::from_nanos(15_500)), "15.500 µs");
160        assert_eq!(format_duration_human(Duration::from_nanos(2_500_000)), "2.500 ms");
161        assert_eq!(format_duration_human(Duration::from_millis(1500)), "1.500 s");
162    }
163
164    #[test]
165    fn test_sub_millisecond_fractional_millis() {
166        let d = Duration::from_micros(25); // 25 µs = 0.025 ms
167        assert_eq!(d.as_millis(), 0); // Demonstrates the original truncation bug
168        assert!((DurationPrecisionExt::as_millis_f64(&d) - 0.025).abs() < 1e-6);
169        assert!((d.as_micros_f64() - 25.0).abs() < 1e-6);
170    }
171
172    #[test]
173    fn test_benchmark_runner() {
174        let mut x = 0u64;
175        let result = PrecisionTimer::benchmark_fn(10_000, || {
176            x = x.wrapping_add(1);
177        });
178        assert_eq!(result.iterations, 10_000);
179        assert!(result.nanos_per_op > 0.0);
180        assert!(result.ops_per_sec > 0.0);
181    }
182}