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
/// Measures the average code execution time in N repetitions.
/// 
/// `bench!(wrapper_func, N, "Prompt")` execute `wrapper_func` N repetitions.
/// 
/// `bench!(wrapper_func, "Prompt")` execute `wrapper_func` 10,000 repetitions.
/// 
/// The result prints to the standard output as `Prompt: xxx.yy ms`.
#[macro_export]
macro_rules! bench {
    ($func:expr, $description:expr) => {
        bench!($func, 10_000, $description);
    };
    ($func:expr, $count:expr, $description:expr) => {
        let n: u32 = $count;
        let start = std::time::Instant::now();
        for _ in 0..n {
            $func();
        }
        println!("{}: {:?}", $description, start.elapsed() / n);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bench_ok() {
        bench!(wrapper, "Var1");
        bench!(wrapper, 1_000, "Var2");
    }

    fn wrapper() {
        for i in 0..1000 {
            let _ = i*i;
        }
    }
}