Skip to content
systemcoding.dev
Performance

Write Your First Microbenchmark With Google Benchmark

Build Google Benchmark 1.9, write a first BM_ function with the state loop, read the Time, CPU and Iterations columns, and avoid beginner traps.

7 min read
Summarize in AI
Flat illustration of a CPU core with its cache levels and main memory, with the C++, Arm and Intel logos.

A microbenchmark measures one small piece of code, such as a function or a data structure operation, in isolation. The hard parts are not the stopwatch. They are deciding how many times to repeat, keeping the compiler from deleting the work, and reporting a number you can compare across runs. Google Benchmark is a C++ library that handles those parts: it chooses the iteration count itself, runs until the measurement is stable, and prints a table. This post builds version 1.9 with CMake, writes a first benchmark comparing two ways to build a string, explains every column of the output and covers the mistakes beginners make. For why a hand-rolled loop is not enough, see why naive timing loops lie.

Install the library

Google Benchmark builds with CMake and needs a C++14 compiler. The simplest integration uses FetchContent, which downloads and builds a pinned release inside your project, so everyone gets the same version. Write this CMakeLists.txt:

CMakeLists.txtcmake
cmake_minimum_required(VERSION 3.20)
project(first_bench CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

if(NOT CMAKE_BUILD_TYPE)
  set(CMAKE_BUILD_TYPE Release)
endif()

include(FetchContent)
set(BENCHMARK_ENABLE_TESTING OFF CACHE BOOL "" FORCE)
FetchContent_Declare(
  googlebenchmark
  GIT_REPOSITORY https://github.com/google/benchmark.git
  GIT_TAG        v1.9.1
)
FetchContent_MakeAvailable(googlebenchmark)

add_executable(bench_strings bench_strings.cpp)
target_link_libraries(bench_strings PRIVATE benchmark::benchmark)

Two lines matter. Defaulting to a Release build means the code is optimized, since benchmarking an unoptimized build measures code you will not ship. And BENCHMARK_ENABLE_TESTING OFF skips the library's own tests, which would pull in extra dependencies.

The smallest benchmark

A benchmark is a function that takes a benchmark::State& and runs the code to measure inside a loop over that state. Here are two ways to build a 100-character string, one that appends character by character and one that reserves the space first:

bench_strings.cppcpp
#include <benchmark/benchmark.h>
#include <string>

static void BM_StringAppend(benchmark::State &state)
{
    for (auto _ : state) {
        std::string s;
        for (int i = 0; i < 100; i++)
            s.push_back('x');
        benchmark::DoNotOptimize(s);
    }
}
BENCHMARK(BM_StringAppend);

static void BM_StringReserve(benchmark::State &state)
{
    for (auto _ : state) {
        std::string s;
        s.reserve(100);
        for (int i = 0; i < 100; i++)
            s.push_back('x');
        benchmark::DoNotOptimize(s);
    }
}
BENCHMARK(BM_StringReserve);

BENCHMARK_MAIN();

Four pieces do all the work. for (auto _ : state) is the measured loop: the library controls how many times it runs and times the whole thing, and the variable _ is unused. Everything before the loop is setup that is not timed, and everything inside is timed on every iteration. benchmark::DoNotOptimize(s) tells the compiler the string is used, so the pushes cannot be deleted. BENCHMARK(...) registers the function by name. BENCHMARK_MAIN() expands to a main that parses command-line flags and runs everything registered.

Build and run:

Shell
cmake -S . -B build
cmake --build build -j
./build/bench_strings

Read the output

Text
2026-11-23T10:14:02+00:00
Running ./build/bench_strings
Run on (8 X 3600 MHz CPU s)
CPU Caches:
  L1 Data 32 KiB (x4)
  L1 Instruction 32 KiB (x4)
  L2 Unified 256 KiB (x4)
  L3 Unified 8192 KiB (x1)
Load Average: 0.52, 0.48, 0.41
------------------------------------------------------------
Benchmark                  Time             CPU   Iterations
------------------------------------------------------------
BM_StringAppend          152 ns          152 ns      4592873
BM_StringReserve         118 ns          118 ns      5921340

The header and the figures here are illustrative; yours reflect your machine. The header records the context, which matters when you compare results later: the CPU count and speed, cache sizes and the load average. A high load average at the start is a warning that other work was competing.

For each benchmark, Time is the average wall-clock time of one iteration of the loop body. CPU is the average CPU time the thread used for one iteration. They agree here because the code never waits. They diverge for code that sleeps or blocks, where wall time exceeds CPU time. Iterations is how many times the library ran the loop to get a stable result. It starts at one and grows, multiplying until the measurement runs for a minimum duration (half a second by default). That is why a fast function shows millions of iterations and a slow one only a few.

The comparison the numbers support is that reserving first saves the string's growth reallocations: the append version reallocates as capacity doubles, and the reserve version allocates once. For strings up to 15 characters, many standard library implementations store the data inline with no allocation at all, which is why a benchmark of tiny strings tells a different story from this 100-character one. Choose sizes that match your real use.

Pass the compiler what it needs

The library measures whatever the compiler generated, so the flags matter. -O2 or -O3 is right for performance questions. CMake's Release type sets -O3 -DNDEBUG for GCC and Clang. If the library was built in debug mode, it prints a warning that the library was built as DEBUG and timings may be affected, which you should treat as a real problem: rebuild with -DCMAKE_BUILD_TYPE=Release. It may also warn that CPU scaling is enabled, meaning the frequency can change during the run, which the post on disabling frequency scaling addresses.

Useful command-line flags

Because BENCHMARK_MAIN parses flags, you can change behavior without recompiling. Run only some benchmarks with a regular expression, repeat the whole set to see variation, and write machine-readable output:

Shell
./build/bench_strings --benchmark_filter=Reserve
./build/bench_strings --benchmark_repetitions=10 --benchmark_report_aggregates_only=true
./build/bench_strings --benchmark_out=run.json --benchmark_out_format=json

With repetitions, the report ends with the mean, median and standard deviation of the per-repetition averages, which is the quickest way to judge how stable a result is. A coefficient of variation of a few percent is typical for a quiet machine; much more tells you to look at the environment. The JSON file is the input for the comparison tool described in comparing benchmark runs with compare.py.

Beginner mistakes

Four problems account for most bad first benchmarks. First, putting setup inside the timed loop: constructing a large vector each iteration measures the construction as well as the operation, and the fix is to build it before the loop or use state.PauseTiming() and state.ResumeTiming(), which are expensive themselves and best avoided for short operations. Second, forgetting DoNotOptimize so the compiler removes the work, which shows up as an implausible result of well under a nanosecond. Third, benchmarking a debug build. Fourth, trusting one run, which brings back everything the previous post warned about. A pair of defensive habits helps: check the assembly of the hot loop once, and run the benchmark more than once before believing a difference smaller than the spread.

Parameterize with arguments

A single input size is a weak benchmark. Google Benchmark lets you register the same function with several arguments, which it passes in through state.range(0). The loop below sweeps the string length:

bench_sizes.cppcpp
#include <benchmark/benchmark.h>
#include <string>

static void BM_StringReserveN(benchmark::State &state)
{
    const int n = static_cast<int>(state.range(0));
    for (auto _ : state) {
        std::string s;
        s.reserve(n);
        for (int i = 0; i < n; i++)
            s.push_back('x');
        benchmark::DoNotOptimize(s);
    }
    state.SetItemsProcessed(state.iterations() * n);
}
BENCHMARK(BM_StringReserveN)->Arg(8)->Arg(64)->Arg(512)->Arg(4096);

Arg adds one run per value. SetItemsProcessed makes the report print items per second, which lets you compare runs of different sizes on one scale. A table of throughput against size shows where a cache level stops fitting the data, and where fixed costs such as the allocation stop mattering.

Keep setup out of the timed region

Anything expensive that does not belong to the operation must stay outside the loop. A benchmark that constructs a large vector inside for (auto _ : state) measures the construction. Build the input before the loop and share it. For per-iteration setup that cannot be shared, such as a fresh unsorted copy for a sort, Google Benchmark offers state.PauseTiming() and state.ResumeTiming(). They are accurate only for operations much longer than the pause itself, because calling them has a cost of its own. For short operations, restructure so the setup is cheap, or accept that you are measuring setup too and compare the two versions on equal terms.

Share

Keep reading

Flat illustration of two options weighed side by side, with the C, C++ and Rust logos.
Performance

Spinlocks vs Mutexes: When Spinning Wins

A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

6 min read

Get new posts by email

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

Unsubscribe in one click. No spam, ever.