Skip to content

Commit

Permalink
Update comparing_functions.md (#706)
Browse files Browse the repository at this point in the history
wrap the for loop index in a black_box to prevent optimizations to happen, which lead to incorrect benchmark comparison. 

On my machine without the blackbox the slow function took 200 picoseconds while the fast took 2.5ns.
  • Loading branch information
Indra-db committed Aug 10, 2023
1 parent bb44f0b commit 1b7ca52
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions book/src/user_guide/comparing_functions.md
Expand Up @@ -5,7 +5,7 @@ graphs to show the differences in performance between them. First, lets create a
benchmark. We can even combine this with benchmarking over a range of inputs.

```rust
use criterion::{criterion_group, criterion_main, Criterion, BenchmarkId};
use criterion::{black_box, criterion_group, criterion_main, Criterion, BenchmarkId};

fn fibonacci_slow(n: u64) -> u64 {
match n {
Expand Down Expand Up @@ -55,9 +55,9 @@ fn bench_fibs(c: &mut Criterion) {
let mut group = c.benchmark_group("Fibonacci");
for i in [20u64, 21u64].iter() {
group.bench_with_input(BenchmarkId::new("Recursive", i), i,
|b, i| b.iter(|| fibonacci_slow(*i)));
|b, i| b.iter(|| fibonacci_slow(black_box(*i))));
group.bench_with_input(BenchmarkId::new("Iterative", i), i,
|b, i| b.iter(|| fibonacci_fast(*i)));
|b, i| b.iter(|| fibonacci_fast(black_box(*i))));
}
group.finish();
}
Expand Down

0 comments on commit 1b7ca52

Please sign in to comment.