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 crate::Source;
use crate::Tracker;
pub struct Timer<T: Tracker, S: Source> {
tracker: T,
source: S,
last: Option<u64>,
}
impl<T: Tracker, S: Source> Timer<T, S> {
pub fn new() -> Self {
Self {
tracker: T::default(),
source: S::default(),
last: None,
}
}
pub fn start(&mut self) {
assert!(self.last.is_none(), "cannot start running timer");
self.last = Some(self.source.get_time());
}
pub fn stop(&mut self) {
let time = self.source.get_time() - self.last.take().expect("cannot stop paused timer");
self.tracker.record(time);
}
pub fn is_running(&self) -> bool {
self.last.is_some()
}
pub fn get_stats(&self) -> T::Statistics {
self.tracker.get_stats(self.last.map(|l| self.source.get_time() - l))
}
pub fn num_nanoseconds(&self) -> u64 {
self.tracker.get(self.last.map(|l| self.source.get_time() - l))
}
pub fn num_microseconds(&self) -> u64 {
self.num_nanoseconds() / 1000
}
pub fn num_milliseconds(&self) -> u64 {
self.num_nanoseconds() / 1000_000
}
pub fn num_seconds(&self) -> u64 {
self.num_nanoseconds() / 1000_000_000
}
pub fn num_minutes(&self) -> u64 {
self.num_nanoseconds() / 60_000_000_000
}
pub fn num_hours(&self) -> u64 {
self.num_nanoseconds() / 3600_000_000_000
}
}