Implement a Simple Benchmark#
This section shows how to implement a simple benchmark using cpp-stat-bench library.
Prerequisites#
Sample Code with Explanation#
Example of a simple benchmark.#
#include <stat_bench/benchmark_macros.h>
[[nodiscard]] int fibonacci(int number);
// Define a benchmark.
// First argument is the name of the group of benchmarks,
// and the second argument is the name of the case of the benchmark.
STAT_BENCH_CASE("Fibonacci", "fibonacci(10)") {
const int number = 10;
// Measure the time to invoke a function.
// The return value is handled by cpp-stat-bench library to prevent
// compilers from optimizing out the function call.
STAT_BENCH_MEASURE() { return fibonacci(number); };
}
// Define another benchmark in the same group.
STAT_BENCH_CASE("Fibonacci", "fibonacci(15)") {
const int number = 15;
STAT_BENCH_MEASURE() { return fibonacci(number); };
}
// Define main function. (Required once in an executable.)
STAT_BENCH_MAIN
int fibonacci(int number) {
if (number < 2) {
return 1;
}
return fibonacci(number - 1) + fibonacci(number - 2);
}
Execution#
You can build the above code and run the resulting executable without arguments to see an output similar to the one below.
Example output to the console.#
cpp-stat-bench 0.21.0
Benchmark start at 2025-02-11T14:12:34.660223+0000
Time resolution: 1.000e-09 sec.
========================================================================================================================
Processing Time
========================================================================================================================
>> Fibonacci
Time [us]
Iterations Samples Mean Std. Err. Max Custom Outputs (mean)
------------------------------------------------------------------------------------------------------------------------
fibonacci(10) 1 100 0.1431 0.0008 0.2140
fibonacci(15) 1 100 1.4411 0.0207 3.4840
========================================================================================================================
Mean Processing Time
========================================================================================================================
>> Fibonacci
Time [us]
Iterations Samples Mean Std. Err. Max Custom Outputs (mean)
------------------------------------------------------------------------------------------------------------------------
fibonacci(10) 1000000 30 0.0009 0.0000 0.0011
fibonacci(15) 1000000 30 0.0012 0.0000 0.0016
Benchmark finished at 2025-02-11T14:12:36.373433+0000