Google Benchmark
Google Benchmark is a open source C++ library for performance benchmarking snippets of C++/C code.
Installation
You can easily add Google Benchmark as a dependency to your CMake C++ project by using FetchContent
in your CMakeLists.txt
file.
set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type")include(FetchContent)set(BENCHMARK_ENABLE_TESTING off)FetchContent_Declare(googlebenchmark GIT_REPOSITORY https://github.com/google/benchmark GIT_TAG main)FetchContent_MakeAvailable(googlebenchmark)
This will automatically download and build Google Benchmark and make it available to your project.
This sets the BUILD_TYPE
to Release
to prevent warnings that Google Benchmark emits when it is built in Debug
mode. set(BENCHMARK_ENABLE_TESTING off)
prevents Google Benchmark from running it’s own unit tests (we can trust it works well!).
Preventing Optimizations
benchmark::ClobberMemory()
can be used to force the compiler to flush pending writes to global memory. This acts as a read/write barrier. This is implemented with std::atomic_signal_fence(std::memory_order_acq_rel);
.
Saving Results to a File
To save Google Benchmark results to a file, you can pass in the --benchmark_out
and --benchmark_out_format
flags to the compiled executable. For example, so save the results to a file called output.json
:
my_benchmark_program --benchmark_out=output.json --benchmark_out_format=json
Footnotes
-
GitHub. google/benchmark [repository]. Retrieved 2025-04-28, from https://github.com/google/benchmark. ↩