iota_utils/
stopwatch.rs

1use std::ops::AddAssign;
2use std::ops::Sub;
3use std::time::{Duration, Instant};
4
5/// Provides a stopwatch for measuring how long things take...
6/// this might seem like a weird addition to the library, but
7/// it was in Jota...so I put it here. If no one uses this, I'll
8/// probably remove it later.
9#[derive(Copy, Clone, Debug)]
10pub struct StopWatch {
11    last_start_time: Instant,
12    running: bool,
13    duration: Duration,
14}
15
16impl Default for StopWatch {
17    fn default() -> Self {
18        Self::new()
19    }
20}
21
22impl StopWatch {
23    /// Creates a new stopwatch
24    pub fn new() -> StopWatch {
25        StopWatch {
26            last_start_time: Instant::now(),
27            running: true,
28            duration: Duration::new(0, 0),
29        }
30    }
31    /// Restarts the stopwatch
32    pub fn restart(&mut self) {
33        self.last_start_time = Instant::now();
34        self.running = true;
35        self.duration = Duration::new(0, 0);
36    }
37    /// Stops the stopwatch and returns the duration
38    pub fn stop(mut self) -> Duration {
39        self.running = false;
40        self.duration
41            .add_assign(Instant::now().sub(self.last_start_time));
42        self.duration
43    }
44    /// Pauses the stopwatch
45    pub fn pause(&mut self) {
46        self.running = false;
47        self.duration
48            .add_assign(Instant::now().sub(self.last_start_time))
49    }
50    /// Resumes the stopwatch
51    pub fn resume(&mut self) {
52        self.running = true;
53        self.last_start_time = Instant::now();
54    }
55    /// Returns the elapsed time so far
56    pub fn elapsed_time(&self) -> Duration {
57        self.duration
58    }
59    /// Checks whether the stopwatch is running
60    pub fn is_running(&self) -> bool {
61        self.running
62    }
63}