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
use std::time::Instant;

pub struct Timer {
    start: Instant,
    end: Instant,
    stopped: bool,
}

impl Timer {
    pub fn new() -> Timer {
        Timer {
            start: Instant::now(),
            end: Instant::now(),
            stopped: false,
        }
    }

    #[allow(dead_code)]
    pub fn start(&mut self) {
        self.start = Instant::now();
        self.end = Instant::now();
    }

    pub fn stop(&mut self) {
        self.end = Instant::now();
        self.stopped = true;
    }

    pub fn elapsed(&self) -> std::time::Duration {
        if !self.stopped {
            return self.start.elapsed();
        }

        self.end.duration_since(self.start)
    }
}

impl Clone for Timer {
    fn clone(&self) -> Self {
        Timer {
            start: self.start,
            end: self.end,
            stopped: self.stopped,
        }
    }
}