Running a Subset of Benchmarks
Runtime and Reporting Considerations
Setup/Teardown
Calculating Asymptotic Complexity
Templated Benchmarks that take arguments
User-Requested Performance Counters
Disabling CPU Frequency Scaling
Reducing Variance in Benchmarks
The library supports multiple output formats. Use the --benchmark_format=<console|json|csv>
flag (or set the BENCHMARK_FORMAT=<console|json|csv>
environment variable) to set the format type. console
is the default format.
The Console format is intended to be a human readable format. By default the format generates color output. Context is output on stderr and the tabular data on stdout. Example tabular output looks like:
The JSON format outputs human readable json split into two top level attributes. The context
attribute contains information about the run in general, including information about the CPU and the date. The benchmarks
attribute contains a list of every benchmark run. Example json output looks like:
The CSV format outputs comma-separated values. The context
is output on stderr and the CSV itself on stdout. Example CSV output looks like:
Write benchmark results to a file with the --benchmark_out=<filename>
option (or set BENCHMARK_OUT
). Specify the output format with --benchmark_out_format={json|console|csv}
(or set BENCHMARK_OUT_FORMAT={json|console|csv}
). Note that the 'csv' reporter is deprecated and the saved .csv
file is not parsable by csv parsers.
Specifying --benchmark_out
does not suppress the console output.
Benchmarks are executed by running the produced binaries. Benchmarks binaries, by default, accept options that may be specified either through their command line interface or by setting environment variables before execution. For every --option_flag=<value>
CLI switch, a corresponding environment variable OPTION_FLAG=<value>
exist and is used as default if set (CLI switches always prevails). A complete list of CLI options is available running benchmarks with the --help
switch.
To confirm that benchmarks can run successfully without needing to wait for multiple repetitions and iterations, the --benchmark_dry_run
flag can be used. This will run the benchmarks as normal, but for 1 iteration and 1 repetition only.
The --benchmark_filter=<regex>
option (or BENCHMARK_FILTER=<regex>
environment variable) can be used to only run the benchmarks that match the specified <regex>
. For example:
It is possible to temporarily disable benchmarks by renaming the benchmark function to have the prefix "DISABLED_". This will cause the benchmark to be skipped at runtime.
It is possible to compare the benchmarking results. See Additional Tooling Documentation
Sometimes it's useful to add extra context to the content printed before the results. By default this section includes information about the CPU on which the benchmarks are running. If you do want to add more context, you can use the benchmark_context
command line flag:
You can get the same effect with the API:
Note that attempts to add a second value with the same key will fail with an error message.
When the benchmark binary is executed, each benchmark function is run serially. The number of iterations to run is determined dynamically by running the benchmark a few times and measuring the time taken and ensuring that the ultimate result will be statistically stable. As such, faster benchmark functions will be run for more iterations than slower benchmark functions, and the number of iterations is thus reported.
In all cases, the number of iterations for which the benchmark is run is governed by the amount of time the benchmark takes. Concretely, the number of iterations is at least one, not more than 1e9, until CPU time is greater than the minimum time, or the wallclock time is 5x minimum time. The minimum time is set per benchmark by calling MinTime
on the registered benchmark object.
Furthermore warming up a benchmark might be necessary in order to get stable results because of e.g caching effects of the code under benchmark. Warming up means running the benchmark a given amount of time, before results are actually taken into account. The amount of time for which the warmup should be run can be set per benchmark by calling MinWarmUpTime
on the registered benchmark object or for all benchmarks using the --benchmark_min_warmup_time
command-line option. Note that MinWarmUpTime
will overwrite the value of --benchmark_min_warmup_time
for the single benchmark. How many iterations the warmup run of each benchmark takes is determined the same way as described in the paragraph above. Per default the warmup phase is set to 0 seconds and is therefore disabled.
Average timings are then reported over the iterations run. If multiple repetitions are requested using the --benchmark_repetitions
command-line option, or at registration time, the benchmark function will be run several times and statistical results across these repetitions will also be reported.
As well as the per-benchmark entries, a preamble in the report will include information about the machine on which the benchmarks are run.
Global setup/teardown specific to each benchmark can be done by passing a callback to Setup/Teardown:
The setup/teardown callbacks will be invoked once for each benchmark. If the benchmark is multi-threaded (will run in k threads), they will be invoked exactly once before each run with k threads.
If the benchmark uses different size groups of threads, the above will be true for each size group.
Eg.,
In this example, DoSetup
and DoTearDown
will be invoked 4 times each, specifically, once for each of this family:
Sometimes a family of benchmarks can be implemented with just one routine that takes an extra argument to specify which one of the family of benchmarks to run. For example, the following code defines a family of benchmarks for measuring the speed of memcpy()
calls of different lengths:
The preceding code is quite repetitive, and can be replaced with the following short-hand. The following invocation will pick a few appropriate arguments in the specified range and will generate a benchmark for each such argument.
By default the arguments in the range are generated in multiples of eight and the command above selects [ 8, 64, 512, 4k, 8k ]. In the following code the range multiplier is changed to multiples of two.
Now arguments generated are [ 8, 16, 32, 64, 128, 256, 512, 1024, 2k, 4k, 8k ].
The preceding code shows a method of defining a sparse range. The following example shows a method of defining a dense range. It is then used to benchmark the performance of std::vector
initialization for uniformly increasing sizes.
Now arguments generated are [ 0, 128, 256, 384, 512, 640, 768, 896, 1024 ].
You might have a benchmark that depends on two or more inputs. For example, the following code defines a family of benchmarks for measuring the speed of set insertion.
The preceding code is quite repetitive, and can be replaced with the following short-hand. The following macro will pick a few appropriate arguments in the product of the two specified ranges and will generate a benchmark for each such pair.
Some benchmarks may require specific argument values that cannot be expressed with Ranges
. In this case, ArgsProduct
offers the ability to generate a benchmark input for each combination in the product of the supplied vectors.
For the most common scenarios, helper methods for creating a list of integers for a given sparse or dense range are provided.
For more complex patterns of inputs, passing a custom function to Apply
allows programmatic specification of an arbitrary set of arguments on which to run the benchmark. The following example enumerates a dense range on one parameter, and a sparse range on the second.
It is possible to define a benchmark that takes an arbitrary number of extra arguments. The BENCHMARK_CAPTURE(func, test_case_name, ...args)
macro creates a benchmark that invokes func
with the benchmark::State
as the first argument followed by the specified args...
. The test_case_name
is appended to the name of the benchmark and should describe the values passed.
Note that elements of ...args
may refer to global variables. Users should avoid modifying global state inside of a benchmark.
Asymptotic complexity might be calculated for a family of benchmarks. The following code will calculate the coefficient for the high-order term in the running time and the normalized root-mean square error of string comparison.
As shown in the following invocation, asymptotic complexity might also be calculated automatically.
The following code will specify asymptotic complexity with a lambda function, that might be used to customize high-order term calculation.
You can change the benchmark's name as follows:
The invocation will execute the benchmark as before using BM_memcpy
but changes the prefix in the report to memcpy
.
This example produces and consumes messages of size sizeof(v)
range_x
times. It also outputs throughput in the absence of multiprogramming.
Three macros are provided for adding benchmark templates.
Sometimes there is a need to template benchmarks, and provide arguments to them.
Fixture tests are created by first defining a type that derives from benchmark::Fixture
and then creating/registering the tests using the following macros:
BENCHMARK_F(ClassName, Method)
BENCHMARK_DEFINE_F(ClassName, Method)
BENCHMARK_REGISTER_F(ClassName, Method)
For Example:
Also you can create templated fixture by using the following macros:
BENCHMARK_TEMPLATE_F(ClassName, Method, ...)
BENCHMARK_TEMPLATE_DEFINE_F(ClassName, Method, ...)
For example:
You can add your own counters with user-defined names. The example below will add columns "Foo", "Bar" and "Baz" in its output:
The state.counters
object is a std::map
with std::string
keys and Counter
values. The latter is a double
-like class, via an implicit conversion to double&
. Thus you can use all of the standard arithmetic assignment operators (=,+=,-=,*=,/=
) to change the value of each counter.
In multithreaded benchmarks, each counter is set on the calling thread only. When the benchmark finishes, the counters from each thread will be summed; the resulting sum is the value which will be shown for the benchmark.
The Counter
constructor accepts three parameters: the value as a double
; a bit flag which allows you to show counters as rates, and/or as per-thread iteration, and/or as per-thread averages, and/or iteration invariants, and/or finally inverting the result; and a flag specifying the 'unit' - i.e. is 1k a 1000 (default, benchmark::Counter::OneK::kIs1000
), or 1024 (benchmark::Counter::OneK::kIs1024
)?
You can use insert()
with std::initializer_list
:
When using the console reporter, by default, user counters are printed at the end after the table, the same way as bytes_processed
and items_processed
. This is best for cases in which there are few counters, or where there are only a couple of lines per benchmark. Here's an example of the default output:
If this doesn't suit you, you can print each counter as a table column by passing the flag --benchmark_counters_tabular=true
to the benchmark application. This is best for cases in which there are a lot of counters, or a lot of lines per individual benchmark. Note that this will trigger a reprinting of the table header any time the counter set changes between individual benchmarks. Here's an example of corresponding output when --benchmark_counters_tabular=true
is passed:
Note above the additional header printed when the benchmark changes from BM_UserCounter
to BM_Factorial
. This is because BM_Factorial
does not have the same counter set as BM_UserCounter
.
In a multithreaded test (benchmark invoked by multiple threads simultaneously), it is guaranteed that none of the threads will start until all have reached the start of the benchmark loop, and all will have finished before any thread exits the benchmark loop. (This behavior is also provided by the KeepRunning()
API) As such, any global setup or teardown can be wrapped in a check against the thread index:
To run the benchmark across a range of thread counts, instead of Threads
, use ThreadRange
. This takes two parameters (min_threads
and max_threads
) and runs the benchmark once for values in the inclusive range. For example:
will run BM_MultiThreaded
with thread counts 1, 2, 4, and 8.
If the benchmarked code itself uses threads and you want to compare it to single-threaded code, you may want to use real-time ("wallclock") measurements for latency comparisons:
Without UseRealTime
, CPU time is used by default.
By default, the CPU timer only measures the time spent by the main thread. If the benchmark itself uses threads internally, this measurement may not be what you are looking for. Instead, there is a way to measure the total CPU usage of the process, by all the threads.
Normally, the entire duration of the work loop (for (auto _ : state) {}
) is measured. But sometimes, it is necessary to do some work inside of that loop, every iteration, but without counting that time to the benchmark time. That is possible, although it is not recommended, since it has high overhead.
For benchmarking something for which neither CPU time nor real-time are correct or accurate enough, completely manual timing is supported using the UseManualTime
function.
When UseManualTime
is used, the benchmarked code must call SetIterationTime
once per iteration of the benchmark loop to report the manually measured time.
An example use case for this is benchmarking GPU execution (e.g. OpenCL or CUDA kernels, OpenGL or Vulkan or Direct3D draw calls), which cannot be accurately measured using CPU time or real-time. Instead, they can be measured accurately using a dedicated API, and these measurement results can be reported back with SetIterationTime
.
If a benchmark runs a few milliseconds it may be hard to visually compare the measured times, since the output data is given in nanoseconds per default. In order to manually set the time unit, you can specify it manually:
Additionally the default time unit can be set globally with the --benchmark_time_unit={ns|us|ms|s}
command line argument. The argument only affects benchmarks where the time unit is not set explicitly.
To prevent a value or expression from being optimized away by the compiler the benchmark::DoNotOptimize(...)
and benchmark::ClobberMemory()
functions can be used.
DoNotOptimize(<expr>)
forces the result of <expr>
to be stored in either memory or a register. For GNU based compilers it acts as read/write barrier for global memory. More specifically it forces the compiler to flush pending writes to memory and reload any other values as necessary.
Note that DoNotOptimize(<expr>)
does not prevent optimizations on <expr>
in any way. <expr>
may even be removed entirely when the result is already known. For example:
The second tool for preventing optimizations is ClobberMemory()
. In essence ClobberMemory()
forces the compiler to perform all pending writes to global memory. Memory managed by block scope objects must be "escaped" using DoNotOptimize(...)
before it can be clobbered. In the below example ClobberMemory()
prevents the call to v.push_back(42)
from being optimized away.
Note that ClobberMemory()
is only available for GNU or MSVC based compilers.
By default each benchmark is run once and that single result is reported. However benchmarks are often noisy and a single result may not be representative of the overall behavior. For this reason it's possible to repeatedly rerun the benchmark.
The number of runs of each benchmark is specified globally by the --benchmark_repetitions
flag or on a per benchmark basis by calling Repetitions
on the registered benchmark object. When a benchmark is run more than once the mean, median, standard deviation and coefficient of variation of the runs will be reported.
Additionally the --benchmark_report_aggregates_only={true|false}
, --benchmark_display_aggregates_only={true|false}
flags or ReportAggregatesOnly(bool)
, DisplayAggregatesOnly(bool)
functions can be used to change how repeated tests are reported. By default the result of each repeated run is reported. When report aggregates only
option is true
, only the aggregates (i.e. mean, median, standard deviation and coefficient of variation, maybe complexity measurements if they were requested) of the runs is reported, to both the reporters - standard output (console), and the file. However when only the display aggregates only
option is true
, only the aggregates are displayed in the standard output, while the file output still contains everything. Calling ReportAggregatesOnly(bool)
/ DisplayAggregatesOnly(bool)
on a registered benchmark object overrides the value of the appropriate flag for that benchmark.
While having these aggregates is nice, this may not be enough for everyone. For example you may want to know what the largest observation is, e.g. because you have some real-time constraints. This is easy. The following code will specify a custom statistic to be calculated, defined by a lambda function.
While usually the statistics produce values in time units, you can also produce percentages:
It's often useful to also track memory usage for benchmarks, alongside CPU performance. For this reason, benchmark offers the RegisterMemoryManager
method that allows a custom MemoryManager
to be injected.
If set, the MemoryManager::Start
and MemoryManager::Stop
methods will be called at the start and end of benchmark runs to allow user code to fill out a report on the number of allocations, bytes used, etc.
This data will then be reported alongside other performance data, currently only when using JSON output.
It's often useful to also profile benchmarks in particular ways, in addition to CPU performance. For this reason, benchmark offers the RegisterProfilerManager
method that allows a custom ProfilerManager
to be injected.
If set, the ProfilerManager::AfterSetupStart
and ProfilerManager::BeforeTeardownStop
methods will be called at the start and end of a separate benchmark run to allow user code to collect and report user-provided profile metrics.
Output collected from this profiling run must be reported separately.
The RegisterBenchmark(name, func, args...)
function provides an alternative way to create and register benchmarks. RegisterBenchmark(name, func, args...)
creates, registers, and returns a pointer to a new benchmark with the specified name
that invokes func(st, args...)
where st
is a benchmark::State
object.
Unlike the BENCHMARK
registration macros, which can only be used at the global scope, the RegisterBenchmark
can be called anywhere. This allows for benchmark tests to be registered programmatically.
Additionally RegisterBenchmark
allows any callable object to be registered as a benchmark. Including capturing lambdas and function objects.
For Example:
When errors caused by external influences, such as file I/O and network communication, occur within a benchmark the State::SkipWithError(const std::string& msg)
function can be used to skip that run of benchmark and report the error. Note that only future iterations of the KeepRunning()
are skipped. For the ranged-for version of the benchmark loop Users must explicitly exit the loop, otherwise all iterations will be performed. Users may explicitly return to exit the benchmark immediately.
The SkipWithError(...)
function may be used at any point within the benchmark, including before and after the benchmark loop. Moreover, if SkipWithError(...)
has been used, it is not required to reach the benchmark loop and one may return from the benchmark function early.
For example:
A ranged-based for loop should be used in preference to the KeepRunning
loop for running the benchmarks. For example:
The reason the ranged-for loop is faster than using KeepRunning
, is because KeepRunning
requires a memory load and store of the iteration count ever iteration, whereas the ranged-for variant is able to keep the iteration count in a register.
For example, an empty inner loop of using the ranged-based for method looks like:
Compared to an empty KeepRunning
loop, which looks like:
Unless C++03 compatibility is required, the ranged-for variant of writing the benchmark loop should be preferred.
If you see this error:
you might want to disable the CPU frequency scaling while running the benchmark, as well as consider other ways to stabilize the performance of your system while benchmarking.
See Reducing Variance for more information.