fast_able/
elapsed_time.rs

1use std::{fmt::Display, time::Duration};
2
3/// Record elapsed time functionality
4/// 记录耗时的功能
5#[derive(Debug, Clone)]
6pub struct ElapsedTime {
7    pub start_time: std::time::Instant,
8    elapsed_logs: Vec<(&'static str, Duration)>,
9    total: Duration,
10}
11
12impl Display for ElapsedTime {
13    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14        f.write_str(&self.print())
15    }
16}
17
18impl ElapsedTime {
19    /// Create a new ElapsedTime instance
20    /// 创建一个新的 ElapsedTime 实例
21    pub fn new(capacity: usize) -> Self {
22        Self {
23            start_time: std::time::Instant::now(),
24            elapsed_logs: Vec::with_capacity(capacity),
25            total: Duration::ZERO,
26        }
27    }
28
29    /// Log a checkpoint with a message
30    /// 记录一个带有消息的检查点
31    pub fn log(&mut self, log: &'static str) {
32        let el = self.start_time.elapsed();
33        let el2 = el - self.total;
34        self.total = el;
35        self.elapsed_logs.push((log, el2));
36    }
37
38    /// Print logs if total time exceeds limit
39    /// 如果总时间超过限制则打印日志
40    pub fn print_limit(&self, limit: Duration) -> Option<String> {
41        if self.total < limit {
42            return None;
43        }
44        Some(self.print())
45    }
46
47    /// Format the logs into a string
48    /// 将日志格式化为字符串
49    pub fn print(&self) -> String {
50        let logs = self
51            .elapsed_logs
52            .iter()
53            .map(|(log, el)| format!("{log}: {el:?}"))
54            .collect::<Vec<_>>()
55            .join(", ");
56
57        format!("Elapsed; total: {:?}, {logs}", self.total)
58    }
59}
60
61#[test]
62fn test_ElapsedTime() {
63    let mut elapsed_time = ElapsedTime::new(10);
64    for i in 0..10 {
65        std::thread::sleep(std::time::Duration::from_millis(i * 100));
66        elapsed_time.log("log");
67    }
68    println!("{}", elapsed_time.print());
69}