scopeclock/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

use std::ops::Drop;
use std::time::Instant;

pub struct ScopeClock {
    scope: &'static str,
    in_time: Instant
}

impl ScopeClock {
    pub fn new(scope: &'static str) -> ScopeClock {
        return ScopeClock {
            scope: scope,
            in_time: Instant::now()
        };
    }

}

impl Drop for ScopeClock {
    fn drop(&mut self) {
        let out_time = Instant::now();
        let duration = out_time - self.in_time;
        println!("{}={}ns", self.scope, duration.as_nanos());
    }
}


#[cfg(test)]
mod tests {
    #[test]
    fn basic() {
        use crate::ScopeClock;

        let _sc = ScopeClock::new("my_scope");
        let x = 3;
        let y = 20;
        let result = x * y;
        println!("Result is {}", result);

        assert!(true);
    }

    #[test]
    fn multi_scope() {
        use crate::ScopeClock;

        {
            let _sc = ScopeClock::new("scope_1");
            let x = 3;
            let y = 20;
            let result = x * y;
            println!("Result 1 is {}", result);
        }

        {
            let _sc = ScopeClock::new("scope_2");
            let x = 33;
            let y = 7;
            let result = x % y;
            println!("Result 2 is {}", result);
        }

        assert!(true);
    }

    #[test]
    fn nested_scope() {
        use crate::ScopeClock;

        {
            let _sc = ScopeClock::new("outer_scope");
            let x = 3;
            let y = 20;
            let result = x * y;
            {
                let _sc = ScopeClock::new("inner_scope");
                let x = 33;
                let y = 7;
                let result = x % y;
                println!("Inner result is {}", result);
            }
            println!("Outer result is {}", result);
        }

        assert!(true);
    }
}