-
Open the Cargo.toml file that has been generated earlier for you.
-
In the bin folder, create a file called benchmarking.rs.
-
Add the following code, and run it with cargo bench:
1 #![feature(test)] 2 // The test crate was primarily designed for 3 // the Rust compiler itself, so it has no stability guaranteed 4 extern crate test; 5 6 pub fn slow_fibonacci_recursive(n: u32) -> u32 { 7 match n { 8 0 => 0, 9 1 => 1, 10 _ => slow_fibonacci_recursive(n - 1) +
slow_fibonacci_recursive(n - 2), 11 } 12 } 13 14 pub fn fibonacci_imperative(n: u32) -> u32 { 15 match n { 16 0 => 0, 17 1 => 1, 18 _ => { 19 let mut penultimate; 20 let mut last = 1; 21 let mut fib = 0; 22 for _ in 0..n { 23 penultimate = last; 24 last = fib; 25 fib = penultimate + last; 26 } 27 fib 28 } 29 } 30 } 31 32 pub fn memoized_fibonacci_recursive(n: u32) -> u32 { 33 fn inner(n: u32, penultimate: u32, last: u32) -> u32 { 34 match n { 35 0 => penultimate, 36 1 => last, 37 _ => inner(n - 1, last, penultimate + last), 38 } 39 } 40 inner(n, 0, 1) 41 } 42 43 pub fn fast_fibonacci_recursive(n: u32) -> u32 { 44 fn inner(n: u32, penultimate: u32, last: u32) -> u32 { 45 match n { 46 0 => last, 47 _ => inner(n - 1, last, penultimate + last), 48 } 49 } 50 match n { 51 0 => 0, 52 _ => inner(n - 1, 0, 1), 53 } 54 }
- Running benchmarks:
56 #[cfg(test)] 57 mod tests { 58 use super::*; 59 use test::Bencher; 60 61 // Functions annotated with the bench attribute will 62 // undergo a performance evaluation when running "cargo bench" 63 #[bench] 64 fn bench_slow_fibonacci_recursive(b: &mut Bencher) { 65 b.iter(|| { 66 // test::block_box is "black box" for the compiler and
LLVM 67 // Telling them to not optimize a variable away 68 let n = test::black_box(20); 69 slow_fibonacci_recursive(n) 70 }); 71 } 72 73 #[bench] 74 fn bench_fibonacci_imperative(b: &mut Bencher) { 75 b.iter(|| { 76 let n = test::black_box(20); 77 fibonacci_imperative(n) 78 }); 79 } 80 81 #[bench] 82 fn bench_memoized_fibonacci_recursive(b: &mut Bencher) { 83 b.iter(|| { 84 let n = test::black_box(20); 85 memoized_fibonacci_recursive(n) 86 }); 87 } 88 89 #[bench] 90 fn bench_fast_fibonacci_recursive(b: &mut Bencher) { 91 b.iter(|| { 92 let n = test::black_box(20); 93 fast_fibonacci_recursive(n) 94 }); 95 } 96 }