fast_able/
elapsed_time.rs1use std::{fmt::Display, time::Duration};
2
3#[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 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 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 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 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}