1use friendly::temporal::HumanDuration;
2use std::fmt;
3use std::time::{Duration, Instant};
4
5#[derive(Debug, Clone)]
7pub struct Timer {
8 started: Instant,
9}
10
11impl Timer {
12 pub fn new() -> Timer {
14 Timer {
15 started: Instant::now(),
16 }
17 }
18
19 pub fn elapsed(&self) -> Duration {
21 self.started.elapsed()
22 }
23
24 pub fn human_elapsed(&self) -> HumanDuration {
26 self.elapsed().into()
27 }
28}
29
30impl fmt::Display for Timer {
31 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32 write!(f, "{}", self.human_elapsed())
33 }
34}
35
36#[cfg(test)]
38pub fn human_time(dur: Duration) -> String {
39 let hd = HumanDuration::from(dur);
40 hd.to_string()
41}
42
43#[test]
44fn test_human_secs() {
45 let s = human_time(Duration::from_secs(10));
46 assert_eq!(s.as_str(), "10.00s");
47}
48
49#[test]
50fn test_human_mins() {
51 let s = human_time(Duration::from_secs(135));
52 assert_eq!(s.as_str(), "2m15.00s");
53}