1#![allow(unused)]
9use log::info;
10use std::time::{Duration, Instant};
11
12#[macro_export]
15macro_rules! profile_start {
16 ($name:ident) => {
17 let $name = TimeLapse::new();
18 };
19}
20
21#[macro_export]
24macro_rules! profile_end {
25 ($name:ident) => {
26 $name.log(stringify!($name));
27 };
28}
29
30pub struct TimeLapse {
35 start_time: Instant,
36}
37
38impl TimeLapse {
39 pub fn new() -> Self {
41 TimeLapse {
42 start_time: Instant::now(),
43 }
44 }
45
46 pub fn elapsed(&self) -> Duration {
48 self.start_time.elapsed()
49 }
50
51 pub fn reset(&mut self) {
53 self.start_time = Instant::now();
54 }
55}
56
57impl std::fmt::Display for TimeLapse {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 write!(f, "Elapsed time: {:?}", self.elapsed())
61 }
62}
63
64impl std::fmt::Debug for TimeLapse {
66 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67 write!(f, "TimeLapse {{ elapsed: {:?} }}", self.elapsed())
68 }
69}
70
71impl std::default::Default for TimeLapse {
73 fn default() -> Self {
74 Self::new()
75 }
76}
77
78impl TimeLapse {
79 pub fn log(&self, name: &str) {
81 info!("TimeLapse {} - Elapsed time: {:?}", name, self.elapsed());
82 }
83}
84
85#[cfg(test)]
86mod tests {
87 use super::*;
88
89 #[test]
90 fn test_profiler() {
91 let profiler = TimeLapse::new();
92 std::thread::sleep(Duration::from_millis(100));
93 assert!(profiler.elapsed().as_millis() >= 100);
94 profiler.log("test");
95 }
96
97 #[test]
98 fn test_profiler_macros() {
99 profile_start!(the_profile);
100 std::thread::sleep(Duration::from_millis(100));
101 assert!(the_profile.elapsed().as_millis() >= 100);
102 profile_end!(the_profile);
103 }
104
105 #[test]
106 fn test_profiler_reset() {
107 let mut profiler = TimeLapse::new();
108 std::thread::sleep(Duration::from_millis(100));
109 profiler.reset();
110 assert!(profiler.elapsed().as_millis() < 50);
111 }
112}