bookdata/util/
timing.rs

1use friendly::temporal::HumanDuration;
2use std::fmt;
3use std::time::{Duration, Instant};
4
5/// A timer for monitoring task completion.
6#[derive(Debug, Clone)]
7pub struct Timer {
8    started: Instant,
9}
10
11impl Timer {
12    /// Create a new timer with defaults.
13    pub fn new() -> Timer {
14        Timer {
15            started: Instant::now(),
16        }
17    }
18
19    /// Get the elapsed time on this timer.
20    pub fn elapsed(&self) -> Duration {
21        self.started.elapsed()
22    }
23
24    /// Get the elapsed time on this timer, wrapped for human presentation.
25    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/// Format a duration with a human-readable string.
37#[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}