1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use std::time::{Instant, Duration};

pub fn start() -> Timer<'static> {
    Timer::start()
}

pub fn start_with_label<'a>(label: &'a str) -> Timer<'a> {
    Timer::with_label(label)
}

pub struct Timer<'a> {
    start: Instant,
    label: Option<&'a str>,
}

impl<'a> Timer<'a> {
    pub fn start() -> Self {
        Self {
            start: Instant::now(),
            label: None,
        }
    }

    pub fn with_label(label: &'a str) -> Self {
        Self {
            start: Instant::now(),
            label: Some(label),
        }
    }

    pub fn stop(self) -> Duration {
        self.start.elapsed()
    }

    pub fn elapsed(&self) -> Duration {
        self.start.elapsed()
    }

    pub fn print_secs(&self) {
        if let Some(label) = self.label {
            println!("{}: {}s", label, self.start.elapsed().as_secs());
        } else {
            println!("{}s", self.start.elapsed().as_secs());
        }
    }

    pub fn print_ms(&self) {
        if let Some(label) = self.label {
            println!("{}: {}ms", label, self.start.elapsed().as_millis());
        } else {
            println!("{}ms", self.start.elapsed().as_millis());
        }
    }

    pub fn print_micros(&self) {
        if let Some(label) = self.label {
            println!("{}: {}μs", label, self.start.elapsed().as_micros());
        } else {
            println!("{}μs", self.start.elapsed().as_micros());
        }
    }

    pub fn print_nanos(&self) {
        if let Some(label) = self.label {
            println!("{}: {}ns", label, self.start.elapsed().as_nanos());
        } else {
            println!("{}ns", self.start.elapsed().as_nanos());
        }
    }
}