1 | use criterion::{criterion_group, BenchmarkId, Criterion}; |
2 | |
3 | fn fibonacci_slow(n: u64) -> u64 { |
4 | match n { |
5 | 0 | 1 => 1, |
6 | n => fibonacci_slow(n - 1) + fibonacci_slow(n - 2), |
7 | } |
8 | } |
9 | |
10 | fn fibonacci_fast(n: u64) -> u64 { |
11 | let mut a = 0; |
12 | let mut b = 1; |
13 | |
14 | match n { |
15 | 0 => b, |
16 | _ => { |
17 | for _ in 0..n { |
18 | let c = a + b; |
19 | a = b; |
20 | b = c; |
21 | } |
22 | b |
23 | } |
24 | } |
25 | } |
26 | |
27 | fn compare_fibonaccis(c: &mut Criterion) { |
28 | let mut group = c.benchmark_group("Fibonacci" ); |
29 | |
30 | group.bench_with_input("Recursive" , &20, |b, i| b.iter(|| fibonacci_slow(*i))); |
31 | group.bench_with_input("Iterative" , &20, |b, i| b.iter(|| fibonacci_fast(*i))); |
32 | } |
33 | fn compare_fibonaccis_group(c: &mut Criterion) { |
34 | let mut group = c.benchmark_group("Fibonacci3" ); |
35 | for i in 20..=21 { |
36 | group.bench_with_input(BenchmarkId::new("Recursive" , i), &i, |b, i| { |
37 | b.iter(|| fibonacci_slow(*i)) |
38 | }); |
39 | group.bench_with_input(BenchmarkId::new("Iterative" , i), &i, |b, i| { |
40 | b.iter(|| fibonacci_fast(*i)) |
41 | }); |
42 | } |
43 | group.finish() |
44 | } |
45 | |
46 | criterion_group!(fibonaccis, compare_fibonaccis, compare_fibonaccis_group,); |
47 | |