benchmark_counters/
stop_watch.rs

1use std::time::{Duration, Instant};
2
3pub struct StopWatch {
4    start_time: Option<Instant>,
5    elapsed: Duration,
6}
7
8impl StopWatch {
9    pub fn new() -> Self {
10        Self {
11            start_time: None,
12            elapsed: Duration::default(),
13        }
14    }
15
16    pub fn start(&mut self) {
17        self.start_time = Some(Instant::now());
18    }
19
20    pub fn stop(&mut self) {
21        self.elapsed = self.elapsed();
22        self.start_time = None;
23    }
24
25    pub fn reset(&mut self) {
26        self.start_time = None;
27        self.elapsed = Duration::default();
28    }
29
30    pub fn elapsed(&self) -> Duration {
31        match self.start_time {
32            Some(t) => t.elapsed() + self.elapsed,
33            None => self.elapsed,
34        }
35    }
36
37    pub fn is_running(&self) -> bool {
38        self.start_time.is_some()
39    }
40}
41
42impl Default for StopWatch {
43    fn default() -> Self {
44        Self::new()
45    }
46}