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#[derive(Debug)]
33pub struct ScopedTimer {
34 start: Instant,
35 #[allow(dead_code)]
36 name: &'static str,
37}
38
39impl ScopedTimer {
40 #[must_use]
46 pub fn new(name: &'static str) -> Self {
47 Self {
48 start: Instant::now(),
49 name,
50 }
51 }
52
53 #[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}