bookdata/util/
timing.rs

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
use friendly::temporal::HumanDuration;
use std::fmt;
use std::time::{Duration, Instant};

/// A timer for monitoring task completion.
#[derive(Debug, Clone)]
pub struct Timer {
    started: Instant,
}

impl Timer {
    /// Create a new timer with defaults.
    pub fn new() -> Timer {
        Timer {
            started: Instant::now(),
        }
    }

    /// Get the elapsed time on this timer.
    pub fn elapsed(&self) -> Duration {
        self.started.elapsed()
    }

    /// Get the elapsed time on this timer, wrapped for human presentation.
    pub fn human_elapsed(&self) -> HumanDuration {
        self.elapsed().into()
    }
}

impl fmt::Display for Timer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.human_elapsed())
    }
}

/// Format a duration with a human-readable string.
#[cfg(test)]
pub fn human_time(dur: Duration) -> String {
    let hd = HumanDuration::from(dur);
    hd.to_string()
}

#[test]
fn test_human_secs() {
    let s = human_time(Duration::from_secs(10));
    assert_eq!(s.as_str(), "10.00s");
}

#[test]
fn test_human_mins() {
    let s = human_time(Duration::from_secs(135));
    assert_eq!(s.as_str(), "2m15.00s");
}