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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use std::fmt::{self, Display, Formatter};
use std::time::{Duration, Instant};
use time::OffsetDateTime;
#[derive(Clone, Copy)]
pub(crate) struct Timer {
start_monotonic: Instant,
start_formattable: OffsetDateTime,
}
impl Timer {
pub(crate) fn new() -> Timer {
Timer {
start_monotonic: Instant::now(),
start_formattable: OffsetDateTime::now_utc(),
}
}
pub(crate) fn elapsed(&self) -> Timing {
let duration = self.start_monotonic.elapsed();
Timing(duration)
}
pub(crate) fn start_time(&self) -> &OffsetDateTime {
&self.start_formattable
}
}
#[derive(Clone, Copy)]
pub(crate) struct Timing(Duration);
impl Display for Timing {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let duration = self.0;
match duration.as_micros() {
i if i < 1000 => {
write!(f, "{}µs", i)
}
i if i < 1_000_000 => {
write!(f, "{:.2}ms", (i as f64) / 1000.0)
}
_ => {
write!(f, "{:.2}s", duration.as_secs_f32())
}
}
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::Timing;
#[test]
fn test_durations() {
let microsecond = Duration::from_micros(1);
let t0 = Timing(microsecond * 555);
assert_eq!(t0.to_string(), "555µs");
let t1 = Timing(microsecond * 666_444);
assert_eq!(t1.to_string(), "666.44ms");
let t2 = Timing(microsecond * 777_444_333);
assert_eq!(t2.to_string(), "777.44s");
}
}