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
use chrono::prelude::*;
use std::fmt::{self, Display, Formatter};
#[derive(Clone, Copy)]
pub struct Timer {
start: DateTime<Utc>,
}
impl Timer {
pub fn new() -> Timer {
Timer { start: Utc::now() }
}
pub fn elapsed(&self) -> Timing {
let duration = Utc::now()
.signed_duration_since(self.start)
.num_microseconds();
match duration {
Some(dur) => Timing::Microseconds(dur),
None => Timing::Invalid,
}
}
pub fn start_time(&self) -> &DateTime<Utc> {
&self.start
}
}
#[derive(Clone, Copy)]
pub enum Timing {
Microseconds(i64),
Invalid,
}
impl Display for Timing {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match *self {
Timing::Microseconds(i) => {
if i < 1000 {
write!(f, "{}µs", i)
} else if i < 1_000_000 {
write!(f, "{:.2}ms", (i as f32) / 1000.0)
} else {
write!(f, "{:.2}s", (i as f32) / 1_000_000.0)
}
}
Timing::Invalid => f.write_str("invalid"),
}
}
}