README.md
1# Benchmark
2[![Build Status](https://travis-ci.org/google/benchmark.svg?branch=master)](https://travis-ci.org/google/benchmark)
3[![Build status](https://ci.appveyor.com/api/projects/status/u0qsyp7t1tk7cpxs/branch/master?svg=true)](https://ci.appveyor.com/project/google/benchmark/branch/master)
4[![Coverage Status](https://coveralls.io/repos/google/benchmark/badge.svg)](https://coveralls.io/r/google/benchmark)
5[![slackin](https://slackin-iqtfqnpzxd.now.sh/badge.svg)](https://slackin-iqtfqnpzxd.now.sh/)
6
7
8A library to benchmark code snippets, similar to unit tests. Example:
9
10```c++
11#include <benchmark/benchmark.h>
12
13static void BM_SomeFunction(benchmark::State& state) {
14 // Perform setup here
15 for (auto _ : state) {
16 // This code gets timed
17 SomeFunction();
18 }
19}
20// Register the function as a benchmark
21BENCHMARK(BM_SomeFunction);
22// Run the benchmark
23BENCHMARK_MAIN();
24```
25
26To get started, see [Requirements](#requirements) and
27[Installation](#installation). See [Usage](#usage) for a full example and the
28[User Guide](#user-guide) for a more comprehensive feature overview.
29
30It may also help to read the [Google Test documentation](https://github.com/google/googletest/blob/master/googletest/docs/primer.md)
31as some of the structural aspects of the APIs are similar.
32
33### Resources
34
35[Discussion group](https://groups.google.com/d/forum/benchmark-discuss)
36
37IRC channel: [freenode](https://freenode.net) #googlebenchmark
38
39[Additional Tooling Documentation](docs/tools.md)
40
41[Assembly Testing Documentation](docs/AssemblyTests.md)
42
43## Requirements
44
45The library can be used with C++03. However, it requires C++11 to build,
46including compiler and standard library support.
47
48The following minimum versions are required to build the library:
49
50* GCC 4.8
51* Clang 3.4
52* Visual Studio 2013
53* Intel 2015 Update 1
54
55## Installation
56
57This describes the installation process using cmake. As pre-requisites, you'll
58need git and cmake installed.
59
60_See [dependencies.md](dependencies.md) for more details regarding supported
61versions of build tools._
62
63```bash
64# Check out the library.
65$ git clone https://github.com/google/benchmark.git
66# Benchmark requires Google Test as a dependency. Add the source tree as a subdirectory.
67$ git clone https://github.com/google/googletest.git benchmark/googletest
68# Make a build directory to place the build output.
69$ mkdir build && cd build
70# Generate a Makefile with cmake.
71# Use cmake -G <generator> to generate a different file type.
72$ cmake ../benchmark
73# Build the library.
74$ make
75```
76This builds the `benchmark` and `benchmark_main` libraries and tests.
77On a unix system, the build directory should now look something like this:
78
79```
80/benchmark
81/build
82 /src
83 /libbenchmark.a
84 /libbenchmark_main.a
85 /test
86 ...
87```
88
89Next, you can run the tests to check the build.
90
91```bash
92$ make test
93```
94
95If you want to install the library globally, also run:
96
97```
98sudo make install
99```
100
101Note that Google Benchmark requires Google Test to build and run the tests. This
102dependency can be provided two ways:
103
104* Checkout the Google Test sources into `benchmark/googletest` as above.
105* Otherwise, if `-DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON` is specified during
106 configuration, the library will automatically download and build any required
107 dependencies.
108
109If you do not wish to build and run the tests, add `-DBENCHMARK_ENABLE_GTEST_TESTS=OFF`
110to `CMAKE_ARGS`.
111
112### Debug vs Release
113
114By default, benchmark builds as a debug library. You will see a warning in the
115output when this is the case. To build it as a release library instead, use:
116
117```
118cmake -DCMAKE_BUILD_TYPE=Release
119```
120
121To enable link-time optimisation, use
122
123```
124cmake -DCMAKE_BUILD_TYPE=Release -DBENCHMARK_ENABLE_LTO=true
125```
126
127If you are using gcc, you might need to set `GCC_AR` and `GCC_RANLIB` cmake
128cache variables, if autodetection fails.
129
130If you are using clang, you may need to set `LLVMAR_EXECUTABLE`,
131`LLVMNM_EXECUTABLE` and `LLVMRANLIB_EXECUTABLE` cmake cache variables.
132
133
134### Stable and Experimental Library Versions
135
136The main branch contains the latest stable version of the benchmarking library;
137the API of which can be considered largely stable, with source breaking changes
138being made only upon the release of a new major version.
139
140Newer, experimental, features are implemented and tested on the
141[`v2` branch](https://github.com/google/benchmark/tree/v2). Users who wish
142to use, test, and provide feedback on the new features are encouraged to try
143this branch. However, this branch provides no stability guarantees and reserves
144the right to change and break the API at any time.
145
146## Usage
147### Basic usage
148Define a function that executes the code to measure, register it as a benchmark
149function using the `BENCHMARK` macro, and ensure an appropriate `main` function
150is available:
151
152```c++
153#include <benchmark/benchmark.h>
154
155static void BM_StringCreation(benchmark::State& state) {
156 for (auto _ : state)
157 std::string empty_string;
158}
159// Register the function as a benchmark
160BENCHMARK(BM_StringCreation);
161
162// Define another benchmark
163static void BM_StringCopy(benchmark::State& state) {
164 std::string x = "hello";
165 for (auto _ : state)
166 std::string copy(x);
167}
168BENCHMARK(BM_StringCopy);
169
170BENCHMARK_MAIN();
171```
172
173To run the benchmark, compile and link against the `benchmark` library
174(libbenchmark.a/.so). If you followed the build steps above, this
175library will be under the build directory you created.
176
177```bash
178# Example on linux after running the build steps above. Assumes the
179# `benchmark` and `build` directories are under the current directory.
180$ g++ -std=c++11 -isystem benchmark/include -Lbuild/src -lpthread \
181 -lbenchmark mybenchmark.cc -o mybenchmark
182```
183
184Alternatively, link against the `benchmark_main` library and remove
185`BENCHMARK_MAIN();` above to get the same behavior.
186
187The compiled executable will run all benchmarks by default. Pass the `--help`
188flag for option information or see the guide below.
189
190### Platform-specific instructions
191
192When the library is built using GCC it is necessary to link with the pthread
193library due to how GCC implements `std::thread`. Failing to link to pthread will
194lead to runtime exceptions (unless you're using libc++), not linker errors. See
195[issue #67](https://github.com/google/benchmark/issues/67) for more details. You
196can link to pthread by adding `-pthread` to your linker command. Note, you can
197also use `-lpthread`, but there are potential issues with ordering of command
198line parameters if you use that.
199
200If you're running benchmarks on Windows, the shlwapi library (`-lshlwapi`) is
201also required.
202
203If you're running benchmarks on solaris, you'll want the kstat library linked in
204too (`-lkstat`).
205
206## User Guide
207
208### Command Line
209[Output Formats](#output-formats)
210
211[Output Files](#output-files)
212
213[Running a Subset of Benchmarks](#running-a-subset-of-benchmarks)
214
215[Result Comparison](#result-comparison)
216
217### Library
218[Runtime and Reporting Considerations](#runtime-and-reporting-considerations)
219
220[Passing Arguments](#passing-arguments)
221
222[Calculating Asymptotic Complexity](#asymptotic-complexity)
223
224[Templated Benchmarks](#templated-benchmarks)
225
226[Fixtures](#fixtures)
227
228[Custom Counters](#custom-counters)
229
230[Multithreaded Benchmarks](#multithreaded-benchmarks)
231
232[CPU Timers](#cpu-timers)
233
234[Manual Timing](#manual-timing)
235
236[Setting the Time Unit](#setting-the-time-unit)
237
238[Preventing Optimization](#preventing-optimization)
239
240[Reporting Statistics](#reporting-statistics)
241
242[Custom Statistics](#custom-statistics)
243
244[Using RegisterBenchmark](#using-register-benchmark)
245
246[Exiting with an Error](#exiting-with-an-error)
247
248[A Faster KeepRunning Loop](#a-faster-keep-running-loop)
249
250[Disabling CPU Frequency Scaling](#disabling-cpu-frequency-scaling)
251
252<a name="output-formats" />
253
254### Output Formats
255
256The library supports multiple output formats. Use the
257`--benchmark_format=<console|json|csv>` flag to set the format type. `console`
258is the default format.
259
260The Console format is intended to be a human readable format. By default
261the format generates color output. Context is output on stderr and the
262tabular data on stdout. Example tabular output looks like:
263```
264Benchmark Time(ns) CPU(ns) Iterations
265----------------------------------------------------------------------
266BM_SetInsert/1024/1 28928 29349 23853 133.097kB/s 33.2742k items/s
267BM_SetInsert/1024/8 32065 32913 21375 949.487kB/s 237.372k items/s
268BM_SetInsert/1024/10 33157 33648 21431 1.13369MB/s 290.225k items/s
269```
270
271The JSON format outputs human readable json split into two top level attributes.
272The `context` attribute contains information about the run in general, including
273information about the CPU and the date.
274The `benchmarks` attribute contains a list of every benchmark run. Example json
275output looks like:
276```json
277{
278 "context": {
279 "date": "2015/03/17-18:40:25",
280 "num_cpus": 40,
281 "mhz_per_cpu": 2801,
282 "cpu_scaling_enabled": false,
283 "build_type": "debug"
284 },
285 "benchmarks": [
286 {
287 "name": "BM_SetInsert/1024/1",
288 "iterations": 94877,
289 "real_time": 29275,
290 "cpu_time": 29836,
291 "bytes_per_second": 134066,
292 "items_per_second": 33516
293 },
294 {
295 "name": "BM_SetInsert/1024/8",
296 "iterations": 21609,
297 "real_time": 32317,
298 "cpu_time": 32429,
299 "bytes_per_second": 986770,
300 "items_per_second": 246693
301 },
302 {
303 "name": "BM_SetInsert/1024/10",
304 "iterations": 21393,
305 "real_time": 32724,
306 "cpu_time": 33355,
307 "bytes_per_second": 1199226,
308 "items_per_second": 299807
309 }
310 ]
311}
312```
313
314The CSV format outputs comma-separated values. The `context` is output on stderr
315and the CSV itself on stdout. Example CSV output looks like:
316```
317name,iterations,real_time,cpu_time,bytes_per_second,items_per_second,label
318"BM_SetInsert/1024/1",65465,17890.7,8407.45,475768,118942,
319"BM_SetInsert/1024/8",116606,18810.1,9766.64,3.27646e+06,819115,
320"BM_SetInsert/1024/10",106365,17238.4,8421.53,4.74973e+06,1.18743e+06,
321```
322
323<a name="output-files" />
324
325### Output Files
326
327Write benchmark results to a file with the `--benchmark_out=<filename>` option.
328Specify the output format with `--benchmark_out_format={json|console|csv}`. Note that Specifying
329`--benchmark_out` does not suppress the console output.
330
331<a name="running-a-subset-of-benchmarks" />
332
333### Running a Subset of Benchmarks
334
335The `--benchmark_filter=<regex>` option can be used to only run the benchmarks
336which match the specified `<regex>`. For example:
337
338```bash
339$ ./run_benchmarks.x --benchmark_filter=BM_memcpy/32
340Run on (1 X 2300 MHz CPU )
3412016-06-25 19:34:24
342Benchmark Time CPU Iterations
343----------------------------------------------------
344BM_memcpy/32 11 ns 11 ns 79545455
345BM_memcpy/32k 2181 ns 2185 ns 324074
346BM_memcpy/32 12 ns 12 ns 54687500
347BM_memcpy/32k 1834 ns 1837 ns 357143
348```
349
350<a name="result-comparison" />
351
352### Result comparison
353
354It is possible to compare the benchmarking results. See [Additional Tooling Documentation](docs/tools.md)
355
356<a name="runtime-and-reporting-considerations" />
357
358### Runtime and Reporting Considerations
359
360When the benchmark binary is executed, each benchmark function is run serially.
361The number of iterations to run is determined dynamically by running the
362benchmark a few times and measuring the time taken and ensuring that the
363ultimate result will be statistically stable. As such, faster benchmark
364functions will be run for more iterations than slower benchmark functions, and
365the number of iterations is thus reported.
366
367In all cases, the number of iterations for which the benchmark is run is
368governed by the amount of time the benchmark takes. Concretely, the number of
369iterations is at least one, not more than 1e9, until CPU time is greater than
370the minimum time, or the wallclock time is 5x minimum time. The minimum time is
371set per benchmark by calling `MinTime` on the registered benchmark object.
372
373Average timings are then reported over the iterations run. If multiple
374repetitions are requested using the `--benchmark_repetitions` command-line
375option, or at registration time, the benchmark function will be run several
376times and statistical results across these repetitions will also be reported.
377
378As well as the per-benchmark entries, a preamble in the report will include
379information about the machine on which the benchmarks are run.
380
381<a name="passing-arguments" />
382
383### Passing Arguments
384
385Sometimes a family of benchmarks can be implemented with just one routine that
386takes an extra argument to specify which one of the family of benchmarks to
387run. For example, the following code defines a family of benchmarks for
388measuring the speed of `memcpy()` calls of different lengths:
389
390```c++
391static void BM_memcpy(benchmark::State& state) {
392 char* src = new char[state.range(0)];
393 char* dst = new char[state.range(0)];
394 memset(src, 'x', state.range(0));
395 for (auto _ : state)
396 memcpy(dst, src, state.range(0));
397 state.SetBytesProcessed(int64_t(state.iterations()) *
398 int64_t(state.range(0)));
399 delete[] src;
400 delete[] dst;
401}
402BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10);
403```
404
405The preceding code is quite repetitive, and can be replaced with the following
406short-hand. The following invocation will pick a few appropriate arguments in
407the specified range and will generate a benchmark for each such argument.
408
409```c++
410BENCHMARK(BM_memcpy)->Range(8, 8<<10);
411```
412
413By default the arguments in the range are generated in multiples of eight and
414the command above selects [ 8, 64, 512, 4k, 8k ]. In the following code the
415range multiplier is changed to multiples of two.
416
417```c++
418BENCHMARK(BM_memcpy)->RangeMultiplier(2)->Range(8, 8<<10);
419```
420Now arguments generated are [ 8, 16, 32, 64, 128, 256, 512, 1024, 2k, 4k, 8k ].
421
422You might have a benchmark that depends on two or more inputs. For example, the
423following code defines a family of benchmarks for measuring the speed of set
424insertion.
425
426```c++
427static void BM_SetInsert(benchmark::State& state) {
428 std::set<int> data;
429 for (auto _ : state) {
430 state.PauseTiming();
431 data = ConstructRandomSet(state.range(0));
432 state.ResumeTiming();
433 for (int j = 0; j < state.range(1); ++j)
434 data.insert(RandomNumber());
435 }
436}
437BENCHMARK(BM_SetInsert)
438 ->Args({1<<10, 128})
439 ->Args({2<<10, 128})
440 ->Args({4<<10, 128})
441 ->Args({8<<10, 128})
442 ->Args({1<<10, 512})
443 ->Args({2<<10, 512})
444 ->Args({4<<10, 512})
445 ->Args({8<<10, 512});
446```
447
448The preceding code is quite repetitive, and can be replaced with the following
449short-hand. The following macro will pick a few appropriate arguments in the
450product of the two specified ranges and will generate a benchmark for each such
451pair.
452
453```c++
454BENCHMARK(BM_SetInsert)->Ranges({{1<<10, 8<<10}, {128, 512}});
455```
456
457For more complex patterns of inputs, passing a custom function to `Apply` allows
458programmatic specification of an arbitrary set of arguments on which to run the
459benchmark. The following example enumerates a dense range on one parameter,
460and a sparse range on the second.
461
462```c++
463static void CustomArguments(benchmark::internal::Benchmark* b) {
464 for (int i = 0; i <= 10; ++i)
465 for (int j = 32; j <= 1024*1024; j *= 8)
466 b->Args({i, j});
467}
468BENCHMARK(BM_SetInsert)->Apply(CustomArguments);
469```
470
471#### Passing Arbitrary Arguments to a Benchmark
472
473In C++11 it is possible to define a benchmark that takes an arbitrary number
474of extra arguments. The `BENCHMARK_CAPTURE(func, test_case_name, ...args)`
475macro creates a benchmark that invokes `func` with the `benchmark::State` as
476the first argument followed by the specified `args...`.
477The `test_case_name` is appended to the name of the benchmark and
478should describe the values passed.
479
480```c++
481template <class ...ExtraArgs>
482void BM_takes_args(benchmark::State& state, ExtraArgs&&... extra_args) {
483 [...]
484}
485// Registers a benchmark named "BM_takes_args/int_string_test" that passes
486// the specified values to `extra_args`.
487BENCHMARK_CAPTURE(BM_takes_args, int_string_test, 42, std::string("abc"));
488```
489Note that elements of `...args` may refer to global variables. Users should
490avoid modifying global state inside of a benchmark.
491
492<a name="asymptotic-complexity" />
493
494### Calculating Asymptotic Complexity (Big O)
495
496Asymptotic complexity might be calculated for a family of benchmarks. The
497following code will calculate the coefficient for the high-order term in the
498running time and the normalized root-mean square error of string comparison.
499
500```c++
501static void BM_StringCompare(benchmark::State& state) {
502 std::string s1(state.range(0), '-');
503 std::string s2(state.range(0), '-');
504 for (auto _ : state) {
505 benchmark::DoNotOptimize(s1.compare(s2));
506 }
507 state.SetComplexityN(state.range(0));
508}
509BENCHMARK(BM_StringCompare)
510 ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity(benchmark::oN);
511```
512
513As shown in the following invocation, asymptotic complexity might also be
514calculated automatically.
515
516```c++
517BENCHMARK(BM_StringCompare)
518 ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity();
519```
520
521The following code will specify asymptotic complexity with a lambda function,
522that might be used to customize high-order term calculation.
523
524```c++
525BENCHMARK(BM_StringCompare)->RangeMultiplier(2)
526 ->Range(1<<10, 1<<18)->Complexity([](int64_t n)->double{return n; });
527```
528
529<a name="templated-benchmarks" />
530
531### Templated Benchmarks
532
533This example produces and consumes messages of size `sizeof(v)` `range_x`
534times. It also outputs throughput in the absence of multiprogramming.
535
536```c++
537template <class Q> void BM_Sequential(benchmark::State& state) {
538 Q q;
539 typename Q::value_type v;
540 for (auto _ : state) {
541 for (int i = state.range(0); i--; )
542 q.push(v);
543 for (int e = state.range(0); e--; )
544 q.Wait(&v);
545 }
546 // actually messages, not bytes:
547 state.SetBytesProcessed(
548 static_cast<int64_t>(state.iterations())*state.range(0));
549}
550BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue<int>)->Range(1<<0, 1<<10);
551```
552
553Three macros are provided for adding benchmark templates.
554
555```c++
556#ifdef BENCHMARK_HAS_CXX11
557#define BENCHMARK_TEMPLATE(func, ...) // Takes any number of parameters.
558#else // C++ < C++11
559#define BENCHMARK_TEMPLATE(func, arg1)
560#endif
561#define BENCHMARK_TEMPLATE1(func, arg1)
562#define BENCHMARK_TEMPLATE2(func, arg1, arg2)
563```
564
565<a name="fixtures" />
566
567### Fixtures
568
569Fixture tests are created by first defining a type that derives from
570`::benchmark::Fixture` and then creating/registering the tests using the
571following macros:
572
573* `BENCHMARK_F(ClassName, Method)`
574* `BENCHMARK_DEFINE_F(ClassName, Method)`
575* `BENCHMARK_REGISTER_F(ClassName, Method)`
576
577For Example:
578
579```c++
580class MyFixture : public benchmark::Fixture {
581public:
582 void SetUp(const ::benchmark::State& state) {
583 }
584
585 void TearDown(const ::benchmark::State& state) {
586 }
587};
588
589BENCHMARK_F(MyFixture, FooTest)(benchmark::State& st) {
590 for (auto _ : st) {
591 ...
592 }
593}
594
595BENCHMARK_DEFINE_F(MyFixture, BarTest)(benchmark::State& st) {
596 for (auto _ : st) {
597 ...
598 }
599}
600/* BarTest is NOT registered */
601BENCHMARK_REGISTER_F(MyFixture, BarTest)->Threads(2);
602/* BarTest is now registered */
603```
604
605#### Templated Fixtures
606
607Also you can create templated fixture by using the following macros:
608
609* `BENCHMARK_TEMPLATE_F(ClassName, Method, ...)`
610* `BENCHMARK_TEMPLATE_DEFINE_F(ClassName, Method, ...)`
611
612For example:
613```c++
614template<typename T>
615class MyFixture : public benchmark::Fixture {};
616
617BENCHMARK_TEMPLATE_F(MyFixture, IntTest, int)(benchmark::State& st) {
618 for (auto _ : st) {
619 ...
620 }
621}
622
623BENCHMARK_TEMPLATE_DEFINE_F(MyFixture, DoubleTest, double)(benchmark::State& st) {
624 for (auto _ : st) {
625 ...
626 }
627}
628
629BENCHMARK_REGISTER_F(MyFixture, DoubleTest)->Threads(2);
630```
631
632<a name="custom-counters" />
633
634### Custom Counters
635
636You can add your own counters with user-defined names. The example below
637will add columns "Foo", "Bar" and "Baz" in its output:
638
639```c++
640static void UserCountersExample1(benchmark::State& state) {
641 double numFoos = 0, numBars = 0, numBazs = 0;
642 for (auto _ : state) {
643 // ... count Foo,Bar,Baz events
644 }
645 state.counters["Foo"] = numFoos;
646 state.counters["Bar"] = numBars;
647 state.counters["Baz"] = numBazs;
648}
649```
650
651The `state.counters` object is a `std::map` with `std::string` keys
652and `Counter` values. The latter is a `double`-like class, via an implicit
653conversion to `double&`. Thus you can use all of the standard arithmetic
654assignment operators (`=,+=,-=,*=,/=`) to change the value of each counter.
655
656In multithreaded benchmarks, each counter is set on the calling thread only.
657When the benchmark finishes, the counters from each thread will be summed;
658the resulting sum is the value which will be shown for the benchmark.
659
660The `Counter` constructor accepts three parameters: the value as a `double`
661; a bit flag which allows you to show counters as rates, and/or as per-thread
662iteration, and/or as per-thread averages, and/or iteration invariants;
663and a flag specifying the 'unit' - i.e. is 1k a 1000 (default,
664`benchmark::Counter::OneK::kIs1000`), or 1024
665(`benchmark::Counter::OneK::kIs1024`)?
666
667```c++
668 // sets a simple counter
669 state.counters["Foo"] = numFoos;
670
671 // Set the counter as a rate. It will be presented divided
672 // by the duration of the benchmark.
673 state.counters["FooRate"] = Counter(numFoos, benchmark::Counter::kIsRate);
674
675 // Set the counter as a thread-average quantity. It will
676 // be presented divided by the number of threads.
677 state.counters["FooAvg"] = Counter(numFoos, benchmark::Counter::kAvgThreads);
678
679 // There's also a combined flag:
680 state.counters["FooAvgRate"] = Counter(numFoos,benchmark::Counter::kAvgThreadsRate);
681
682 // This says that we process with the rate of state.range(0) bytes every iteration:
683 state.counters["BytesProcessed"] = Counter(state.range(0), benchmark::Counter::kIsIterationInvariantRate, benchmark::Counter::OneK::kIs1024);
684```
685
686When you're compiling in C++11 mode or later you can use `insert()` with
687`std::initializer_list`:
688
689```c++
690 // With C++11, this can be done:
691 state.counters.insert({{"Foo", numFoos}, {"Bar", numBars}, {"Baz", numBazs}});
692 // ... instead of:
693 state.counters["Foo"] = numFoos;
694 state.counters["Bar"] = numBars;
695 state.counters["Baz"] = numBazs;
696```
697
698#### Counter Reporting
699
700When using the console reporter, by default, user counters are are printed at
701the end after the table, the same way as ``bytes_processed`` and
702``items_processed``. This is best for cases in which there are few counters,
703or where there are only a couple of lines per benchmark. Here's an example of
704the default output:
705
706```
707------------------------------------------------------------------------------
708Benchmark Time CPU Iterations UserCounters...
709------------------------------------------------------------------------------
710BM_UserCounter/threads:8 2248 ns 10277 ns 68808 Bar=16 Bat=40 Baz=24 Foo=8
711BM_UserCounter/threads:1 9797 ns 9788 ns 71523 Bar=2 Bat=5 Baz=3 Foo=1024m
712BM_UserCounter/threads:2 4924 ns 9842 ns 71036 Bar=4 Bat=10 Baz=6 Foo=2
713BM_UserCounter/threads:4 2589 ns 10284 ns 68012 Bar=8 Bat=20 Baz=12 Foo=4
714BM_UserCounter/threads:8 2212 ns 10287 ns 68040 Bar=16 Bat=40 Baz=24 Foo=8
715BM_UserCounter/threads:16 1782 ns 10278 ns 68144 Bar=32 Bat=80 Baz=48 Foo=16
716BM_UserCounter/threads:32 1291 ns 10296 ns 68256 Bar=64 Bat=160 Baz=96 Foo=32
717BM_UserCounter/threads:4 2615 ns 10307 ns 68040 Bar=8 Bat=20 Baz=12 Foo=4
718BM_Factorial 26 ns 26 ns 26608979 40320
719BM_Factorial/real_time 26 ns 26 ns 26587936 40320
720BM_CalculatePiRange/1 16 ns 16 ns 45704255 0
721BM_CalculatePiRange/8 73 ns 73 ns 9520927 3.28374
722BM_CalculatePiRange/64 609 ns 609 ns 1140647 3.15746
723BM_CalculatePiRange/512 4900 ns 4901 ns 142696 3.14355
724```
725
726If this doesn't suit you, you can print each counter as a table column by
727passing the flag `--benchmark_counters_tabular=true` to the benchmark
728application. This is best for cases in which there are a lot of counters, or
729a lot of lines per individual benchmark. Note that this will trigger a
730reprinting of the table header any time the counter set changes between
731individual benchmarks. Here's an example of corresponding output when
732`--benchmark_counters_tabular=true` is passed:
733
734```
735---------------------------------------------------------------------------------------
736Benchmark Time CPU Iterations Bar Bat Baz Foo
737---------------------------------------------------------------------------------------
738BM_UserCounter/threads:8 2198 ns 9953 ns 70688 16 40 24 8
739BM_UserCounter/threads:1 9504 ns 9504 ns 73787 2 5 3 1
740BM_UserCounter/threads:2 4775 ns 9550 ns 72606 4 10 6 2
741BM_UserCounter/threads:4 2508 ns 9951 ns 70332 8 20 12 4
742BM_UserCounter/threads:8 2055 ns 9933 ns 70344 16 40 24 8
743BM_UserCounter/threads:16 1610 ns 9946 ns 70720 32 80 48 16
744BM_UserCounter/threads:32 1192 ns 9948 ns 70496 64 160 96 32
745BM_UserCounter/threads:4 2506 ns 9949 ns 70332 8 20 12 4
746--------------------------------------------------------------
747Benchmark Time CPU Iterations
748--------------------------------------------------------------
749BM_Factorial 26 ns 26 ns 26392245 40320
750BM_Factorial/real_time 26 ns 26 ns 26494107 40320
751BM_CalculatePiRange/1 15 ns 15 ns 45571597 0
752BM_CalculatePiRange/8 74 ns 74 ns 9450212 3.28374
753BM_CalculatePiRange/64 595 ns 595 ns 1173901 3.15746
754BM_CalculatePiRange/512 4752 ns 4752 ns 147380 3.14355
755BM_CalculatePiRange/4k 37970 ns 37972 ns 18453 3.14184
756BM_CalculatePiRange/32k 303733 ns 303744 ns 2305 3.14162
757BM_CalculatePiRange/256k 2434095 ns 2434186 ns 288 3.1416
758BM_CalculatePiRange/1024k 9721140 ns 9721413 ns 71 3.14159
759BM_CalculatePi/threads:8 2255 ns 9943 ns 70936
760```
761Note above the additional header printed when the benchmark changes from
762``BM_UserCounter`` to ``BM_Factorial``. This is because ``BM_Factorial`` does
763not have the same counter set as ``BM_UserCounter``.
764
765<a name="multithreaded-benchmarks"/>
766
767### Multithreaded Benchmarks
768
769In a multithreaded test (benchmark invoked by multiple threads simultaneously),
770it is guaranteed that none of the threads will start until all have reached
771the start of the benchmark loop, and all will have finished before any thread
772exits the benchmark loop. (This behavior is also provided by the `KeepRunning()`
773API) As such, any global setup or teardown can be wrapped in a check against the thread
774index:
775
776```c++
777static void BM_MultiThreaded(benchmark::State& state) {
778 if (state.thread_index == 0) {
779 // Setup code here.
780 }
781 for (auto _ : state) {
782 // Run the test as normal.
783 }
784 if (state.thread_index == 0) {
785 // Teardown code here.
786 }
787}
788BENCHMARK(BM_MultiThreaded)->Threads(2);
789```
790
791If the benchmarked code itself uses threads and you want to compare it to
792single-threaded code, you may want to use real-time ("wallclock") measurements
793for latency comparisons:
794
795```c++
796BENCHMARK(BM_test)->Range(8, 8<<10)->UseRealTime();
797```
798
799Without `UseRealTime`, CPU time is used by default.
800
801<a name="cpu-timers" />
802
803### CPU Timers
804
805By default, the CPU timer only measures the time spent by the main thread.
806If the benchmark itself uses threads internally, this measurement may not
807be what you are looking for. Instead, there is a way to measure the total
808CPU usage of the process, by all the threads.
809
810```c++
811void callee(int i);
812
813static void MyMain(int size) {
814#pragma omp parallel for
815 for(int i = 0; i < size; i++)
816 callee(i);
817}
818
819static void BM_OpenMP(benchmark::State& state) {
820 for (auto _ : state)
821 MyMain(state.range(0);
822}
823
824// Measure the time spent by the main thread, use it to decide for how long to
825// run the benchmark loop. Depending on the internal implementation detail may
826// measure to anywhere from near-zero (the overhead spent before/after work
827// handoff to worker thread[s]) to the whole single-thread time.
828BENCHMARK(BM_OpenMP)->Range(8, 8<<10);
829
830// Measure the user-visible time, the wall clock (literally, the time that
831// has passed on the clock on the wall), use it to decide for how long to
832// run the benchmark loop. This will always be meaningful, an will match the
833// time spent by the main thread in single-threaded case, in general decreasing
834// with the number of internal threads doing the work.
835BENCHMARK(BM_OpenMP)->Range(8, 8<<10)->UseRealTime();
836
837// Measure the total CPU consumption, use it to decide for how long to
838// run the benchmark loop. This will always measure to no less than the
839// time spent by the main thread in single-threaded case.
840BENCHMARK(BM_OpenMP)->Range(8, 8<<10)->MeasureProcessCPUTime();
841
842// A mixture of the last two. Measure the total CPU consumption, but use the
843// wall clock to decide for how long to run the benchmark loop.
844BENCHMARK(BM_OpenMP)->Range(8, 8<<10)->MeasureProcessCPUTime()->UseRealTime();
845```
846
847#### Controlling Timers
848
849Normally, the entire duration of the work loop (`for (auto _ : state) {}`)
850is measured. But sometimes, it is necessary to do some work inside of
851that loop, every iteration, but without counting that time to the benchmark time.
852That is possible, althought it is not recommended, since it has high overhead.
853
854```c++
855static void BM_SetInsert_With_Timer_Control(benchmark::State& state) {
856 std::set<int> data;
857 for (auto _ : state) {
858 state.PauseTiming(); // Stop timers. They will not count until they are resumed.
859 data = ConstructRandomSet(state.range(0)); // Do something that should not be measured
860 state.ResumeTiming(); // And resume timers. They are now counting again.
861 // The rest will be measured.
862 for (int j = 0; j < state.range(1); ++j)
863 data.insert(RandomNumber());
864 }
865}
866BENCHMARK(BM_SetInsert_With_Timer_Control)->Ranges({{1<<10, 8<<10}, {128, 512}});
867```
868
869<a name="manual-timing" />
870
871### Manual Timing
872
873For benchmarking something for which neither CPU time nor real-time are
874correct or accurate enough, completely manual timing is supported using
875the `UseManualTime` function.
876
877When `UseManualTime` is used, the benchmarked code must call
878`SetIterationTime` once per iteration of the benchmark loop to
879report the manually measured time.
880
881An example use case for this is benchmarking GPU execution (e.g. OpenCL
882or CUDA kernels, OpenGL or Vulkan or Direct3D draw calls), which cannot
883be accurately measured using CPU time or real-time. Instead, they can be
884measured accurately using a dedicated API, and these measurement results
885can be reported back with `SetIterationTime`.
886
887```c++
888static void BM_ManualTiming(benchmark::State& state) {
889 int microseconds = state.range(0);
890 std::chrono::duration<double, std::micro> sleep_duration {
891 static_cast<double>(microseconds)
892 };
893
894 for (auto _ : state) {
895 auto start = std::chrono::high_resolution_clock::now();
896 // Simulate some useful workload with a sleep
897 std::this_thread::sleep_for(sleep_duration);
898 auto end = std::chrono::high_resolution_clock::now();
899
900 auto elapsed_seconds =
901 std::chrono::duration_cast<std::chrono::duration<double>>(
902 end - start);
903
904 state.SetIterationTime(elapsed_seconds.count());
905 }
906}
907BENCHMARK(BM_ManualTiming)->Range(1, 1<<17)->UseManualTime();
908```
909
910<a name="setting-the-time-unit" />
911
912### Setting the Time Unit
913
914If a benchmark runs a few milliseconds it may be hard to visually compare the
915measured times, since the output data is given in nanoseconds per default. In
916order to manually set the time unit, you can specify it manually:
917
918```c++
919BENCHMARK(BM_test)->Unit(benchmark::kMillisecond);
920```
921
922<a name="preventing-optimization" />
923
924### Preventing Optimization
925
926To prevent a value or expression from being optimized away by the compiler
927the `benchmark::DoNotOptimize(...)` and `benchmark::ClobberMemory()`
928functions can be used.
929
930```c++
931static void BM_test(benchmark::State& state) {
932 for (auto _ : state) {
933 int x = 0;
934 for (int i=0; i < 64; ++i) {
935 benchmark::DoNotOptimize(x += i);
936 }
937 }
938}
939```
940
941`DoNotOptimize(<expr>)` forces the *result* of `<expr>` to be stored in either
942memory or a register. For GNU based compilers it acts as read/write barrier
943for global memory. More specifically it forces the compiler to flush pending
944writes to memory and reload any other values as necessary.
945
946Note that `DoNotOptimize(<expr>)` does not prevent optimizations on `<expr>`
947in any way. `<expr>` may even be removed entirely when the result is already
948known. For example:
949
950```c++
951 /* Example 1: `<expr>` is removed entirely. */
952 int foo(int x) { return x + 42; }
953 while (...) DoNotOptimize(foo(0)); // Optimized to DoNotOptimize(42);
954
955 /* Example 2: Result of '<expr>' is only reused */
956 int bar(int) __attribute__((const));
957 while (...) DoNotOptimize(bar(0)); // Optimized to:
958 // int __result__ = bar(0);
959 // while (...) DoNotOptimize(__result__);
960```
961
962The second tool for preventing optimizations is `ClobberMemory()`. In essence
963`ClobberMemory()` forces the compiler to perform all pending writes to global
964memory. Memory managed by block scope objects must be "escaped" using
965`DoNotOptimize(...)` before it can be clobbered. In the below example
966`ClobberMemory()` prevents the call to `v.push_back(42)` from being optimized
967away.
968
969```c++
970static void BM_vector_push_back(benchmark::State& state) {
971 for (auto _ : state) {
972 std::vector<int> v;
973 v.reserve(1);
974 benchmark::DoNotOptimize(v.data()); // Allow v.data() to be clobbered.
975 v.push_back(42);
976 benchmark::ClobberMemory(); // Force 42 to be written to memory.
977 }
978}
979```
980
981Note that `ClobberMemory()` is only available for GNU or MSVC based compilers.
982
983<a name="reporting-statistics" />
984
985### Statistics: Reporting the Mean, Median and Standard Deviation of Repeated Benchmarks
986
987By default each benchmark is run once and that single result is reported.
988However benchmarks are often noisy and a single result may not be representative
989of the overall behavior. For this reason it's possible to repeatedly rerun the
990benchmark.
991
992The number of runs of each benchmark is specified globally by the
993`--benchmark_repetitions` flag or on a per benchmark basis by calling
994`Repetitions` on the registered benchmark object. When a benchmark is run more
995than once the mean, median and standard deviation of the runs will be reported.
996
997Additionally the `--benchmark_report_aggregates_only={true|false}`,
998`--benchmark_display_aggregates_only={true|false}` flags or
999`ReportAggregatesOnly(bool)`, `DisplayAggregatesOnly(bool)` functions can be
1000used to change how repeated tests are reported. By default the result of each
1001repeated run is reported. When `report aggregates only` option is `true`,
1002only the aggregates (i.e. mean, median and standard deviation, maybe complexity
1003measurements if they were requested) of the runs is reported, to both the
1004reporters - standard output (console), and the file.
1005However when only the `display aggregates only` option is `true`,
1006only the aggregates are displayed in the standard output, while the file
1007output still contains everything.
1008Calling `ReportAggregatesOnly(bool)` / `DisplayAggregatesOnly(bool)` on a
1009registered benchmark object overrides the value of the appropriate flag for that
1010benchmark.
1011
1012<a name="custom-statistics" />
1013
1014### Custom Statistics
1015
1016While having mean, median and standard deviation is nice, this may not be
1017enough for everyone. For example you may want to know what the largest
1018observation is, e.g. because you have some real-time constraints. This is easy.
1019The following code will specify a custom statistic to be calculated, defined
1020by a lambda function.
1021
1022```c++
1023void BM_spin_empty(benchmark::State& state) {
1024 for (auto _ : state) {
1025 for (int x = 0; x < state.range(0); ++x) {
1026 benchmark::DoNotOptimize(x);
1027 }
1028 }
1029}
1030
1031BENCHMARK(BM_spin_empty)
1032 ->ComputeStatistics("max", [](const std::vector<double>& v) -> double {
1033 return *(std::max_element(std::begin(v), std::end(v)));
1034 })
1035 ->Arg(512);
1036```
1037
1038<a name="using-register-benchmark" />
1039
1040### Using RegisterBenchmark(name, fn, args...)
1041
1042The `RegisterBenchmark(name, func, args...)` function provides an alternative
1043way to create and register benchmarks.
1044`RegisterBenchmark(name, func, args...)` creates, registers, and returns a
1045pointer to a new benchmark with the specified `name` that invokes
1046`func(st, args...)` where `st` is a `benchmark::State` object.
1047
1048Unlike the `BENCHMARK` registration macros, which can only be used at the global
1049scope, the `RegisterBenchmark` can be called anywhere. This allows for
1050benchmark tests to be registered programmatically.
1051
1052Additionally `RegisterBenchmark` allows any callable object to be registered
1053as a benchmark. Including capturing lambdas and function objects.
1054
1055For Example:
1056```c++
1057auto BM_test = [](benchmark::State& st, auto Inputs) { /* ... */ };
1058
1059int main(int argc, char** argv) {
1060 for (auto& test_input : { /* ... */ })
1061 benchmark::RegisterBenchmark(test_input.name(), BM_test, test_input);
1062 benchmark::Initialize(&argc, argv);
1063 benchmark::RunSpecifiedBenchmarks();
1064}
1065```
1066
1067<a name="exiting-with-an-error" />
1068
1069### Exiting with an Error
1070
1071When errors caused by external influences, such as file I/O and network
1072communication, occur within a benchmark the
1073`State::SkipWithError(const char* msg)` function can be used to skip that run
1074of benchmark and report the error. Note that only future iterations of the
1075`KeepRunning()` are skipped. For the ranged-for version of the benchmark loop
1076Users must explicitly exit the loop, otherwise all iterations will be performed.
1077Users may explicitly return to exit the benchmark immediately.
1078
1079The `SkipWithError(...)` function may be used at any point within the benchmark,
1080including before and after the benchmark loop.
1081
1082For example:
1083
1084```c++
1085static void BM_test(benchmark::State& state) {
1086 auto resource = GetResource();
1087 if (!resource.good()) {
1088 state.SkipWithError("Resource is not good!");
1089 // KeepRunning() loop will not be entered.
1090 }
1091 for (state.KeepRunning()) {
1092 auto data = resource.read_data();
1093 if (!resource.good()) {
1094 state.SkipWithError("Failed to read data!");
1095 break; // Needed to skip the rest of the iteration.
1096 }
1097 do_stuff(data);
1098 }
1099}
1100
1101static void BM_test_ranged_fo(benchmark::State & state) {
1102 state.SkipWithError("test will not be entered");
1103 for (auto _ : state) {
1104 state.SkipWithError("Failed!");
1105 break; // REQUIRED to prevent all further iterations.
1106 }
1107}
1108```
1109<a name="a-faster-keep-running-loop" />
1110
1111### A Faster KeepRunning Loop
1112
1113In C++11 mode, a ranged-based for loop should be used in preference to
1114the `KeepRunning` loop for running the benchmarks. For example:
1115
1116```c++
1117static void BM_Fast(benchmark::State &state) {
1118 for (auto _ : state) {
1119 FastOperation();
1120 }
1121}
1122BENCHMARK(BM_Fast);
1123```
1124
1125The reason the ranged-for loop is faster than using `KeepRunning`, is
1126because `KeepRunning` requires a memory load and store of the iteration count
1127ever iteration, whereas the ranged-for variant is able to keep the iteration count
1128in a register.
1129
1130For example, an empty inner loop of using the ranged-based for method looks like:
1131
1132```asm
1133# Loop Init
1134 mov rbx, qword ptr [r14 + 104]
1135 call benchmark::State::StartKeepRunning()
1136 test rbx, rbx
1137 je .LoopEnd
1138.LoopHeader: # =>This Inner Loop Header: Depth=1
1139 add rbx, -1
1140 jne .LoopHeader
1141.LoopEnd:
1142```
1143
1144Compared to an empty `KeepRunning` loop, which looks like:
1145
1146```asm
1147.LoopHeader: # in Loop: Header=BB0_3 Depth=1
1148 cmp byte ptr [rbx], 1
1149 jne .LoopInit
1150.LoopBody: # =>This Inner Loop Header: Depth=1
1151 mov rax, qword ptr [rbx + 8]
1152 lea rcx, [rax + 1]
1153 mov qword ptr [rbx + 8], rcx
1154 cmp rax, qword ptr [rbx + 104]
1155 jb .LoopHeader
1156 jmp .LoopEnd
1157.LoopInit:
1158 mov rdi, rbx
1159 call benchmark::State::StartKeepRunning()
1160 jmp .LoopBody
1161.LoopEnd:
1162```
1163
1164Unless C++03 compatibility is required, the ranged-for variant of writing
1165the benchmark loop should be preferred.
1166
1167<a name="disabling-cpu-frequency-scaling" />
1168
1169### Disabling CPU Frequency Scaling
1170If you see this error:
1171```
1172***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead.
1173```
1174you might want to disable the CPU frequency scaling while running the benchmark:
1175```bash
1176sudo cpupower frequency-set --governor performance
1177./mybench
1178sudo cpupower frequency-set --governor powersave
1179```
1180