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
use std::time::Instant;
/// A way to track the passage of real time.
#[derive(Clone)]
pub struct Timer {
start_time: Instant,
is_running: bool,
}
impl Timer {
/// Creates a new `Timer` instance that isn't started. A `Timer` must be started before it'll give any readings
/// on elapsed time.
pub fn new() -> Self {
Self {
start_time: Instant::now(),
is_running: false,
}
}
/// Creates a new `Timer` and starts it.
pub fn start_new() -> Self {
Self {
start_time: Instant::now(),
is_running: true,
}
}
/// Starts the timer. This must be done before the timer will start giving you measured
/// time on calls to elapsed methods. Has no effect on a timer that's already running.
pub fn start(&mut self) {
self.start_time = Instant::now();
self.is_running = true;
}
/// Stops the timer. Any future calls to elapsed methods will effectively give 0.
pub fn stop(&mut self) {
self.is_running = false;
}
/// Resets the timer such that its elapsed time at the moment of this call would be 0.
/// The timer continues to run after this call.
pub fn restart(&mut self) {
self.start_time = Instant::now();
self.is_running = true;
}
pub fn elapsed_seconds(&self) -> u64 {
if self.is_running {
self.start_time.elapsed().as_secs()
} else {
0
}
}
pub fn elapsed_millis(&self) -> u128 {
if self.is_running {
self.start_time.elapsed().as_millis()
} else {
0
}
}
/// Whether the timer is currently running. A Timer must be running to report on elapsed time.
pub fn is_running(&self) -> bool {
self.is_running
}
}