fast_able/
elapsed_time.rs

1use std::{fmt::Display, time::Duration};
2
3// 记录耗时的功能
4#[derive(Debug, Clone)]
5pub struct ElapsedTime {
6    pub start_time: std::time::Instant,
7    elapsed_logs: Vec<(&'static str, Duration)>,
8    total: Duration,
9}
10
11impl Display for ElapsedTime {
12    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13        f.write_str(&self.print())
14    }
15}
16
17impl ElapsedTime {
18    pub fn new(capacity: usize) -> Self {
19        Self {
20            start_time: std::time::Instant::now(),
21            elapsed_logs: Vec::with_capacity(capacity),
22            total: Duration::ZERO,
23        }
24    }
25
26    pub fn log(&mut self, log: &'static str) {
27        let el = self.start_time.elapsed();
28        let el2 = el - self.total;
29        self.total = el;
30        self.elapsed_logs.push((log, el2));
31    }
32
33    pub fn print_limit(&self, limit: Duration) -> Option<String> {
34        if self.total < limit {
35            return None;
36        }
37        Some(self.print())
38    }
39
40    pub fn print(&self) -> String {
41        let logs = self
42            .elapsed_logs
43            .iter()
44            .map(|(log, el)| format!("{log}: {el:?}"))
45            .collect::<Vec<_>>()
46            .join(", ");
47
48        format!("Elapsed; total: {:?}, {logs}", self.total)
49    }
50}
51
52#[test]
53fn test_ElapsedTime() {
54    let mut elapsed_time = ElapsedTime::new(10);
55    for i in 0..10 {
56        std::thread::sleep(std::time::Duration::from_millis(i * 100));
57        elapsed_time.log("log");
58    }
59    println!("{}", elapsed_time.print());
60}