book/src/user_guide/migrating_from_libtest.md
This page shows an example of converting a libtest or bencher benchmark to use Criterion.rs.
We'll start with this benchmark as an example:
#![feature(test)]
extern crate test;
use test::Bencher;
use test::black_box;
fn fibonacci(n: u64) -> u64 {
match n {
0 => 1,
1 => 1,
n => fibonacci(n-1) + fibonacci(n-2),
}
}
#[bench]
fn bench_fib(b: &mut Bencher) {
b.iter(|| fibonacci(black_box(20)));
}
The first thing to do is update the Cargo.toml to disable the libtest
benchmark harness:
[[bench]]
name = "example"
harness = false
We also need to add Criterion.rs to the dev-dependencies section of Cargo.toml:
[dev-dependencies]
criterion = "0.5.1"
The next step is to update the imports:
use criterion::{criterion_group, criterion_main, Criterion};
use std::hint::black_box;
Then, we can change the bench_fib function. Remove the #[bench] and change
the argument to &mut Criterion instead. The contents of this function need to
change as well:
fn bench_fib(c: &mut Criterion) {
c.bench_function("fib 20", |b| b.iter(|| fibonacci(black_box(20))));
}
Finally, we need to invoke some macros to generate a main function, since we no longer have libtest to provide one:
criterion_group!(benches, bench_fib);
criterion_main!(benches);
And that's it! The complete migrated benchmark code is below:
use criterion::{criterion_group, criterion_main, Criterion};
use std::hint::black_box;
fn fibonacci(n: u64) -> u64 {
match n {
0 => 1,
1 => 1,
n => fibonacci(n-1) + fibonacci(n-2),
}
}
fn bench_fib(c: &mut Criterion) {
c.bench_function("fib 20", |b| b.iter(|| fibonacci(black_box(20))));
}
criterion_group!(benches, bench_fib);
criterion_main!(benches);