scopeclock/
lib.rs

1
2use std::ops::Drop;
3use std::time::Instant;
4
5pub struct ScopeClock {
6    scope: &'static str,
7    in_time: Instant
8}
9
10impl ScopeClock {
11    pub fn new(scope: &'static str) -> ScopeClock {
12        return ScopeClock {
13            scope: scope,
14            in_time: Instant::now()
15        };
16    }
17
18}
19
20impl Drop for ScopeClock {
21    fn drop(&mut self) {
22        let out_time = Instant::now();
23        let duration = out_time - self.in_time;
24        println!("{}={}ns", self.scope, duration.as_nanos());
25    }
26}
27
28
29#[cfg(test)]
30mod tests {
31    #[test]
32    fn basic() {
33        use crate::ScopeClock;
34
35        let _sc = ScopeClock::new("my_scope");
36        let x = 3;
37        let y = 20;
38        let result = x * y;
39        println!("Result is {}", result);
40
41        assert!(true);
42    }
43
44    #[test]
45    fn multi_scope() {
46        use crate::ScopeClock;
47
48        {
49            let _sc = ScopeClock::new("scope_1");
50            let x = 3;
51            let y = 20;
52            let result = x * y;
53            println!("Result 1 is {}", result);
54        }
55
56        {
57            let _sc = ScopeClock::new("scope_2");
58            let x = 33;
59            let y = 7;
60            let result = x % y;
61            println!("Result 2 is {}", result);
62        }
63
64        assert!(true);
65    }
66
67    #[test]
68    fn nested_scope() {
69        use crate::ScopeClock;
70
71        {
72            let _sc = ScopeClock::new("outer_scope");
73            let x = 3;
74            let y = 20;
75            let result = x * y;
76            {
77                let _sc = ScopeClock::new("inner_scope");
78                let x = 33;
79                let y = 7;
80                let result = x % y;
81                println!("Inner result is {}", result);
82            }
83            println!("Outer result is {}", result);
84        }
85
86        assert!(true);
87    }
88}