Skip to content

Commit 29c5f02

Browse files
committed
perf(bench): prevent constant-folding of fib input across iterations
The recursive fibonacci benchmarks passed a loop-invariant `n` to fibonacci_recursive, letting the compiler hoist or constant-fold the entire computation out of the measurement loop. Marking `n` with DoNotOptimize forces the input to be treated as opaque on every iteration, so each call actually executes the recursion.
1 parent 476e75c commit 29c5f02

1 file changed

Lines changed: 2 additions & 0 deletions

File tree

examples/google_benchmark_cmake/fibonacci_bench.hpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ static uint64_t fibonacci_recursive(int n) {
1010
static void BM_FibonacciRecursive(benchmark::State& state) {
1111
int n = static_cast<int>(state.range(0));
1212
for (auto _ : state) {
13+
benchmark::DoNotOptimize(n);
1314
uint64_t result = fibonacci_recursive(n);
1415
benchmark::DoNotOptimize(result);
1516
}
@@ -21,6 +22,7 @@ BENCHMARK(BM_FibonacciRecursive)->Arg(35)->MinTime(5);
2122
static void BM_FibonacciRecursive_Darwin(benchmark::State& state) {
2223
int n = static_cast<int>(state.range(0));
2324
for (auto _ : state) {
25+
benchmark::DoNotOptimize(n);
2426
uint64_t result = fibonacci_recursive(n);
2527
benchmark::DoNotOptimize(result);
2628
}

0 commit comments

Comments
 (0)