time_dilation/
lib.rs

1use std::time::{Duration, Instant};
2
3#[allow(dead_code)]
4fn format_duration(nanos: f64) -> String {
5    if nanos < 1_000.0 {
6        format!("{nanos:.2} ns")
7    } else if nanos < 100_000.0 {
8        format!("{:.2} μs", nanos / 1_000.0)
9    } else if nanos < 1_000_000_000.0 {
10        format!("{:.2} ms", nanos / 1_000_000.0)
11    } else {
12        format!("{:.2} s", nanos / 1_000_000_000.0)
13    }
14}
15
16#[cfg(feature = "enable_summary")]
17pub fn summary(name: &str, total_execution_time: Duration) {
18    let duration = total_execution_time;
19    let total_nanos = duration.as_nanos() as f64;
20
21    println!(
22        "timer '{}' completed in {}",
23        name,
24        format_duration(total_nanos),
25    );
26}
27
28/// A simple timer that records elapsed time from its creation until it's dropped.
29///
30/// If the `enable_summary` feature is active, it prints the elapsed time
31/// when dropped.
32#[derive(Debug)]
33pub struct ScopedTimer {
34    start: Instant,
35    #[allow(dead_code)]
36    name: &'static str,
37}
38
39impl ScopedTimer {
40    /// Creates a new timer and records the start time.
41    ///
42    /// # Arguments
43    ///
44    /// * `name` - A static string slice used to identify the timer in the summary output.
45    #[must_use]
46    pub fn new(name: &'static str) -> Self {
47        Self {
48            start: Instant::now(),
49            name,
50        }
51    }
52
53    /// Manually get the elapsed duration without dropping the timer.
54    #[must_use]
55    pub fn elapsed(&self) -> Duration {
56        self.start.elapsed()
57    }
58}
59
60impl Drop for ScopedTimer {
61    fn drop(&mut self) {
62        #[cfg(feature = "enable_summary")]
63        {
64            let elapsed = self.start.elapsed();
65            summary(self.name, elapsed);
66        }
67    }
68}