criterion

How to benchmark functions using criterion library?

1
use criterion::{black_box, criterion_group, criterion_main, Criterion};
2
​
3
pub fn fib(n: i32) -> i32 {
4
if n > 1 {
5
fib(n - 1) + fib(n - 2)
6
} else {
7
1
8
}
9
}
10
​
11
pub fn fib_fast(n: i32) -> i32 {
12
let mut a = 1;
13
let mut b = 1;
14
​
15
for _ in 0..n {
16
b += a;
17
a = b - a;
18
}
19
​
20
a
21
}
22
​
23
fn criterion_fib_slow(c: &mut Criterion) {
24
c.bench_function("fib 10", |b| b.iter(|| fib(black_box(10))));
25
}
26
​
27
fn criterion_fib_fast(c: &mut Criterion) {
28
c.bench_function("fib_fast 10", |b| b.iter(|| fib_fast(black_box(10))));
29
}
30
​
31
criterion_group!(benches, criterion_fib_fast, criterion_fib_slow);
32
criterion_main!(benches);
Copied!
Add following dependencies to the Cargo.toml.
1
[dev-dependencies]
2
criterion = "0.3.1"
3
​
4
[[bench]]
5
name = "lib"
6
path = "src/lib.rs"
7
harness = false
Copied!
Benchmarks can be run by cargo bench.
Last modified 1yr ago
Copy link