Top Related Projects
mimalloc is a compact general purpose allocator with excellent performance.
A modern formatting library
GoogleTest - Google Testing and Mocking Framework
A modern, C++-native, test framework for unit-tests, TDD and BDD - using C++14, C++17 and later (C++11 support is in v2.x branch, and C++03 on the Catch1.x branch)
Abseil Common Libraries (C++)
An open-source C++ library developed and used at Facebook.
Quick Overview
Google Benchmark is a microbenchmarking library for C++. It provides a framework for measuring and comparing the performance of different C++ functions and algorithms. The library is designed to be easy to use and provides a wide range of features to help developers optimize their code.
Pros
- Accurate Measurements: Google Benchmark uses a sophisticated timing mechanism to provide accurate and reliable performance measurements.
- Flexible and Customizable: The library offers a wide range of options and settings to customize the benchmarking process, allowing developers to tailor the tests to their specific needs.
- Cross-Platform Support: Google Benchmark is designed to work on a variety of platforms, including Windows, macOS, and Linux, making it a versatile tool for developers.
- Extensive Documentation: The project has comprehensive documentation, including detailed guides, examples, and API references, making it easy for developers to get started and understand the library's features.
Cons
- Complexity: While the library is powerful, it can be complex to set up and configure, especially for developers who are new to microbenchmarking.
- Overhead: The benchmarking process itself can introduce some overhead, which may affect the accuracy of the measurements, especially for very fast operations.
- Limited Language Support: Google Benchmark is primarily focused on C++, and while it can be used with other languages through bindings, the support may not be as comprehensive as for C++.
- Potential for Misuse: Microbenchmarking can be a powerful tool, but it can also be misused if the tests are not designed carefully, leading to misleading or inaccurate results.
Code Examples
Here are a few examples of how to use Google Benchmark:
- Basic Benchmark:
#include <benchmark/benchmark.h>
static void BM_StringCreation(benchmark::State& state) {
for (auto _ : state)
std::string empty_string;
}
BENCHMARK(BM_StringCreation);
BENCHMARK_MAIN();
This code creates a simple benchmark that measures the time it takes to create an empty string.
- Parameterized Benchmark:
#include <benchmark/benchmark.h>
static void BM_StringLength(benchmark::State& state) {
std::string s(state.range(0), 'x');
for (auto _ : state)
benchmark::DoNotOptimize(s.length());
}
BENCHMARK(BM_StringLength)->Range(1, 1 << 10);
This code creates a parameterized benchmark that measures the time it takes to get the length of a string, with the string size as a parameter.
- Reporting Custom Metrics:
#include <benchmark/benchmark.h>
static void BM_MemcpySmall(benchmark::State& state) {
char src[32], dst[32];
for (auto _ : state)
benchmark::DoNotOptimize(memcpy(dst, src, state.range(0)));
state.SetBytesProcessed(state.iterations() * state.range(0));
}
BENCHMARK(BM_MemcpySmall)->Range(1, 1 << 10);
This code creates a benchmark that measures the performance of the memcpy
function, and reports the number of bytes processed as a custom metric.
Getting Started
To get started with Google Benchmark, follow these steps:
- Clone the repository:
git clone https://github.com/google/benchmark.git
- Build the library:
cd benchmark
cmake -E make_directory "build"
cmake -E chdir "build" cmake -DCMAKE_BUILD_TYPE=Release ../
cmake --build "build" --config Release
- Run the tests:
cd build
ctest -C Release
- Include the library in your C++ project:
#include <benchmark/benchmark.h>
- Write your benchmarks and link against the Google Benchmark library:
g++ -std=c++11 -I/path/to/benchmark/include benchmark_example.cpp -L/path/to/benchmark/build/src -lbenchmark -lpthrea
Competitor Comparisons
mimalloc is a compact general purpose allocator with excellent performance.
Pros of mimalloc
- Focused on memory allocation performance, which can significantly improve overall application speed
- Designed for concurrent and parallel workloads, making it suitable for modern multi-threaded applications
- Offers a drop-in replacement for malloc, making it easy to integrate into existing projects
Cons of mimalloc
- More specialized in scope compared to benchmark's general-purpose benchmarking capabilities
- May require more careful consideration of memory usage patterns to fully leverage its benefits
- Less extensive documentation and community support compared to benchmark
Code Comparison
mimalloc:
#include <mimalloc.h>
void* ptr = mi_malloc(sizeof(int));
mi_free(ptr);
benchmark:
#include <benchmark/benchmark.h>
static void BM_SomeFunction(benchmark::State& state) {
for (auto _ : state) {
// Code to benchmark
}
}
BENCHMARK(BM_SomeFunction);
While both projects aim to improve performance, they serve different purposes. mimalloc focuses on efficient memory allocation, while benchmark provides a framework for measuring and comparing code performance across various metrics.
A modern formatting library
Pros of fmt
- Focuses on fast and safe string formatting, offering a more modern alternative to printf
- Provides a wide range of formatting options and customization capabilities
- Supports compile-time format string checks for improved safety
Cons of fmt
- Limited to string formatting and output, not a general-purpose benchmarking tool
- May require more setup and integration for specific use cases compared to Benchmark
- Less suitable for performance measurement and comparison of code snippets
Code Comparison
fmt:
#include <fmt/core.h>
std::string s = fmt::format("The answer is {}.", 42);
fmt::print("Hello, {}!", "world");
Benchmark:
#include <benchmark/benchmark.h>
static void BM_SomeFunction(benchmark::State& state) {
for (auto _ : state) {
// Code to be benchmarked
}
}
BENCHMARK(BM_SomeFunction);
Summary
fmt is a powerful string formatting library, while Benchmark is designed for microbenchmarking. fmt excels in creating formatted strings and output, offering safety and flexibility. Benchmark, on the other hand, provides a robust framework for measuring and comparing the performance of code snippets. The choice between the two depends on the specific needs of the project: string manipulation and output (fmt) or performance measurement (Benchmark).
GoogleTest - Google Testing and Mocking Framework
Pros of GoogleTest
- More comprehensive testing framework with support for various test types (unit, integration, etc.)
- Extensive assertion macros and matchers for flexible test case creation
- Better suited for complex test scenarios and larger codebases
Cons of GoogleTest
- Steeper learning curve due to more features and complexity
- Potentially slower test execution compared to Benchmark's focused performance testing
- May require more setup and configuration for simple test cases
Code Comparison
GoogleTest example:
TEST(FactorialTest, HandlesZeroInput) {
EXPECT_EQ(Factorial(0), 1);
}
TEST(FactorialTest, HandlesPositiveInput) {
EXPECT_EQ(Factorial(1), 1);
EXPECT_EQ(Factorial(2), 2);
EXPECT_EQ(Factorial(3), 6);
}
Benchmark example:
static void BM_StringCreation(benchmark::State& state) {
for (auto _ : state)
std::string empty_string;
}
BENCHMARK(BM_StringCreation);
static void BM_StringCopy(benchmark::State& state) {
std::string x = "hello";
for (auto _ : state)
std::string copy(x);
}
BENCHMARK(BM_StringCopy);
A modern, C++-native, test framework for unit-tests, TDD and BDD - using C++14, C++17 and later (C++11 support is in v2.x branch, and C++03 on the Catch1.x branch)
Pros of Catch2
- Header-only library, making it easy to integrate into projects
- Supports a wide range of test types, including unit tests, BDD-style tests, and property-based testing
- Extensive assertion macros and matchers for flexible test writing
Cons of Catch2
- Not specifically designed for microbenchmarking, which is Benchmark's primary focus
- May have slightly higher overhead for simple tests compared to Benchmark
Code Comparison
Catch2:
#include <catch2/catch_test_macros.hpp>
TEST_CASE("Addition is correct") {
REQUIRE(1 + 1 == 2);
}
Benchmark:
#include <benchmark/benchmark.h>
static void BM_Addition(benchmark::State& state) {
for (auto _ : state) {
benchmark::DoNotOptimize(1 + 1);
}
}
BENCHMARK(BM_Addition);
Summary
Catch2 is a versatile testing framework suitable for various testing needs, while Benchmark is specifically designed for microbenchmarking. Catch2 offers more flexibility in test types and assertions, but may not be as optimized for performance measurements as Benchmark. The choice between the two depends on whether the primary goal is comprehensive testing (Catch2) or precise performance benchmarking (Benchmark).
Abseil Common Libraries (C++)
Pros of Abseil
- Broader scope: Offers a comprehensive set of C++ library components
- Active development: Regularly updated with new features and improvements
- Google-backed: Developed and maintained by Google, ensuring high quality
Cons of Abseil
- Larger codebase: More complex to integrate and maintain
- Steeper learning curve: Requires more time to understand and utilize effectively
- Potential conflicts: May overlap with existing standard library components
Code Comparison
Abseil (string manipulation):
#include "absl/strings/str_cat.h"
std::string result = absl::StrCat("Hello, ", name, "!");
Benchmark (performance measurement):
#include <benchmark/benchmark.h>
static void BM_StringCreation(benchmark::State& state) {
for (auto _ : state)
std::string empty_string;
}
BENCHMARK(BM_StringCreation);
Summary
Abseil is a comprehensive C++ library offering various components, while Benchmark focuses specifically on microbenchmarking. Abseil provides a wider range of functionality but may be more complex to integrate. Benchmark is simpler and more focused, making it easier to use for its specific purpose of performance testing.
An open-source C++ library developed and used at Facebook.
Pros of Folly
- Broader scope: Folly is a comprehensive C++ library with various utilities, while Benchmark focuses solely on microbenchmarking
- Active development: Folly has more frequent updates and a larger contributor base
- Production-tested: Widely used in Facebook's infrastructure, ensuring reliability at scale
Cons of Folly
- Steeper learning curve: Due to its extensive feature set, Folly can be more complex to learn and use
- Larger footprint: Folly's comprehensive nature means it has a larger codebase and potential impact on build times
Code Comparison
Folly (using folly::Benchmark
):
BENCHMARK(MyFunction) {
for (int i = 0; i < 1000; ++i) {
doSomething();
}
}
Benchmark:
static void BM_MyFunction(benchmark::State& state) {
for (auto _ : state) {
for (int i = 0; i < 1000; ++i) {
doSomething();
}
}
}
BENCHMARK(BM_MyFunction);
Both libraries provide similar functionality for benchmarking, but Benchmark offers a more focused and streamlined approach specifically for performance testing. Folly's benchmarking capabilities are part of a larger ecosystem of utilities, which may be beneficial for projects already using other Folly components.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Benchmark
A library to benchmark code snippets, similar to unit tests. Example:
#include <benchmark/benchmark.h>
static void BM_SomeFunction(benchmark::State& state) {
// Perform setup here
for (auto _ : state) {
// This code gets timed
SomeFunction();
}
}
// Register the function as a benchmark
BENCHMARK(BM_SomeFunction);
// Run the benchmark
BENCHMARK_MAIN();
Getting Started
To get started, see Requirements and Installation. See Usage for a full example and the User Guide for a more comprehensive feature overview.
It may also help to read the Google Test documentation as some of the structural aspects of the APIs are similar.
Resources
IRC channels:
- libera #benchmark
Additional Tooling Documentation
Assembly Testing Documentation
Building and installing Python bindings
Requirements
The library can be used with C++03. However, it requires C++14 to build, including compiler and standard library support.
See dependencies.md for more details regarding supported compilers and standards.
If you have need for a particular compiler to be supported, patches are very welcome.
See Platform-Specific Build Instructions.
Installation
This describes the installation process using cmake. As pre-requisites, you'll need git and cmake installed.
See dependencies.md for more details regarding supported versions of build tools.
# Check out the library.
$ git clone https://github.com/google/benchmark.git
# Go to the library root directory
$ cd benchmark
# Make a build directory to place the build output.
$ cmake -E make_directory "build"
# Generate build system files with cmake, and download any dependencies.
$ cmake -E chdir "build" cmake -DBENCHMARK_DOWNLOAD_DEPENDENCIES=on -DCMAKE_BUILD_TYPE=Release ../
# or, starting with CMake 3.13, use a simpler form:
# cmake -DCMAKE_BUILD_TYPE=Release -S . -B "build"
# Build the library.
$ cmake --build "build" --config Release
This builds the benchmark
and benchmark_main
libraries and tests.
On a unix system, the build directory should now look something like this:
/benchmark
/build
/src
/libbenchmark.a
/libbenchmark_main.a
/test
...
Next, you can run the tests to check the build.
$ cmake -E chdir "build" ctest --build-config Release
If you want to install the library globally, also run:
sudo cmake --build "build" --config Release --target install
Note that Google Benchmark requires Google Test to build and run the tests. This dependency can be provided two ways:
- Checkout the Google Test sources into
benchmark/googletest
. - Otherwise, if
-DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON
is specified during configuration as above, the library will automatically download and build any required dependencies.
If you do not wish to build and run the tests, add -DBENCHMARK_ENABLE_GTEST_TESTS=OFF
to CMAKE_ARGS
.
Debug vs Release
By default, benchmark builds as a debug library. You will see a warning in the
output when this is the case. To build it as a release library instead, add
-DCMAKE_BUILD_TYPE=Release
when generating the build system files, as shown
above. The use of --config Release
in build commands is needed to properly
support multi-configuration tools (like Visual Studio for example) and can be
skipped for other build systems (like Makefile).
To enable link-time optimisation, also add -DBENCHMARK_ENABLE_LTO=true
when
generating the build system files.
If you are using gcc, you might need to set GCC_AR
and GCC_RANLIB
cmake
cache variables, if autodetection fails.
If you are using clang, you may need to set LLVMAR_EXECUTABLE
,
LLVMNM_EXECUTABLE
and LLVMRANLIB_EXECUTABLE
cmake cache variables.
To enable sanitizer checks (eg., asan
and tsan
), add:
-DCMAKE_C_FLAGS="-g -O2 -fno-omit-frame-pointer -fsanitize=address -fsanitize=thread -fno-sanitize-recover=all"
-DCMAKE_CXX_FLAGS="-g -O2 -fno-omit-frame-pointer -fsanitize=address -fsanitize=thread -fno-sanitize-recover=all "
Stable and Experimental Library Versions
The main branch contains the latest stable version of the benchmarking library; the API of which can be considered largely stable, with source breaking changes being made only upon the release of a new major version.
Newer, experimental, features are implemented and tested on the
v2
branch. Users who wish
to use, test, and provide feedback on the new features are encouraged to try
this branch. However, this branch provides no stability guarantees and reserves
the right to change and break the API at any time.
Usage
Basic usage
Define a function that executes the code to measure, register it as a benchmark
function using the BENCHMARK
macro, and ensure an appropriate main
function
is available:
#include <benchmark/benchmark.h>
static void BM_StringCreation(benchmark::State& state) {
for (auto _ : state)
std::string empty_string;
}
// Register the function as a benchmark
BENCHMARK(BM_StringCreation);
// Define another benchmark
static void BM_StringCopy(benchmark::State& state) {
std::string x = "hello";
for (auto _ : state)
std::string copy(x);
}
BENCHMARK(BM_StringCopy);
BENCHMARK_MAIN();
To run the benchmark, compile and link against the benchmark
library
(libbenchmark.a/.so). If you followed the build steps above, this library will
be under the build directory you created.
# Example on linux after running the build steps above. Assumes the
# `benchmark` and `build` directories are under the current directory.
$ g++ mybenchmark.cc -std=c++11 -isystem benchmark/include \
-Lbenchmark/build/src -lbenchmark -lpthread -o mybenchmark
Alternatively, link against the benchmark_main
library and remove
BENCHMARK_MAIN();
above to get the same behavior.
The compiled executable will run all benchmarks by default. Pass the --help
flag for option information or see the User Guide.
Usage with CMake
If using CMake, it is recommended to link against the project-provided
benchmark::benchmark
and benchmark::benchmark_main
targets using
target_link_libraries
.
It is possible to use find_package
to import an installed version of the
library.
find_package(benchmark REQUIRED)
Alternatively, add_subdirectory
will incorporate the library directly in
to one's CMake project.
add_subdirectory(benchmark)
Either way, link to the library as follows.
target_link_libraries(MyTarget benchmark::benchmark)
Top Related Projects
mimalloc is a compact general purpose allocator with excellent performance.
A modern formatting library
GoogleTest - Google Testing and Mocking Framework
A modern, C++-native, test framework for unit-tests, TDD and BDD - using C++14, C++17 and later (C++11 support is in v2.x branch, and C++03 on the Catch1.x branch)
Abseil Common Libraries (C++)
An open-source C++ library developed and used at Facebook.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot