Skip to content
systemcoding.dev
Performance

Report items per second with state.SetItemsProcessed

Make Google Benchmark print items per second by calling state.SetItemsProcessed after the loop, so results compare across input sizes.

1 min read
Summarize in AI

A time per iteration is hard to compare when the input size changes between runs. Tell the library how many items each iteration handled and it prints a rate in its own column.

cpp
#include <benchmark/benchmark.h>
#include <numeric>
#include <vector>

static void BM_Sum(benchmark::State& state) {
    std::vector<int> v(state.range(0), 1);
    for (auto _ : state) {
        benchmark::DoNotOptimize(std::accumulate(v.begin(), v.end(), 0));
    }
    state.SetItemsProcessed(int64_t(state.iterations()) * state.range(0));
}
BENCHMARK(BM_Sum)->Arg(1 << 10)->Arg(1 << 16);
BENCHMARK_MAIN();
Text
---------------------------------------------------------------------
Benchmark              Time             CPU   Iterations items_per_second
---------------------------------------------------------------------
BM_Sum/1024          312 ns          312 ns      2243480       3.28G/s
BM_Sum/65536       19800 ns        19800 ns        35310       3.31G/s

The figures are an example. The rate is the total items divided by the benchmark's time, so the two sizes land on nearly the same value, which is what a linear-time loop should do. Multiply by state.iterations() after the loop, because the library chooses that number itself while it searches for a stable run length. A rate that drops sharply at a larger size is a cache boundary, and a time per iteration alone would have hidden it. Written for Google Benchmark 1.9; see the user guide.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.