5 [Output Formats](#output-formats)
7 [Output Files](#output-files)
9 [Running Benchmarks](#running-benchmarks)
11 [Running a Subset of Benchmarks](#running-a-subset-of-benchmarks)
13 [Result Comparison](#result-comparison)
15 [Extra Context](#extra-context)
19 [Runtime and Reporting Considerations](#runtime-and-reporting-considerations)
21 [Setup/Teardown](#setupteardown)
23 [Passing Arguments](#passing-arguments)
25 [Custom Benchmark Name](#custom-benchmark-name)
27 [Calculating Asymptotic Complexity](#asymptotic-complexity)
29 [Templated Benchmarks](#templated-benchmarks)
33 [Custom Counters](#custom-counters)
35 [Multithreaded Benchmarks](#multithreaded-benchmarks)
37 [CPU Timers](#cpu-timers)
39 [Manual Timing](#manual-timing)
41 [Setting the Time Unit](#setting-the-time-unit)
43 [Random Interleaving](random_interleaving.md)
45 [User-Requested Performance Counters](perf_counters.md)
47 [Preventing Optimization](#preventing-optimization)
49 [Reporting Statistics](#reporting-statistics)
51 [Custom Statistics](#custom-statistics)
53 [Using RegisterBenchmark](#using-register-benchmark)
55 [Exiting with an Error](#exiting-with-an-error)
57 [A Faster KeepRunning Loop](#a-faster-keep-running-loop)
59 [Disabling CPU Frequency Scaling](#disabling-cpu-frequency-scaling)
62 <a name="output-formats" />
66 The library supports multiple output formats. Use the
67 `--benchmark_format=<console|json|csv>` flag (or set the
68 `BENCHMARK_FORMAT=<console|json|csv>` environment variable) to set
69 the format type. `console` is the default format.
71 The Console format is intended to be a human readable format. By default
72 the format generates color output. Context is output on stderr and the
73 tabular data on stdout. Example tabular output looks like:
76 Benchmark Time(ns) CPU(ns) Iterations
77 ----------------------------------------------------------------------
78 BM_SetInsert/1024/1 28928 29349 23853 133.097kB/s 33.2742k items/s
79 BM_SetInsert/1024/8 32065 32913 21375 949.487kB/s 237.372k items/s
80 BM_SetInsert/1024/10 33157 33648 21431 1.13369MB/s 290.225k items/s
83 The JSON format outputs human readable json split into two top level attributes.
84 The `context` attribute contains information about the run in general, including
85 information about the CPU and the date.
86 The `benchmarks` attribute contains a list of every benchmark run. Example json
92 "date": "2015/03/17-18:40:25",
95 "cpu_scaling_enabled": false,
100 "name": "BM_SetInsert/1024/1",
104 "bytes_per_second": 134066,
105 "items_per_second": 33516
108 "name": "BM_SetInsert/1024/8",
112 "bytes_per_second": 986770,
113 "items_per_second": 246693
116 "name": "BM_SetInsert/1024/10",
120 "bytes_per_second": 1199226,
121 "items_per_second": 299807
127 The CSV format outputs comma-separated values. The `context` is output on stderr
128 and the CSV itself on stdout. Example CSV output looks like:
131 name,iterations,real_time,cpu_time,bytes_per_second,items_per_second,label
132 "BM_SetInsert/1024/1",65465,17890.7,8407.45,475768,118942,
133 "BM_SetInsert/1024/8",116606,18810.1,9766.64,3.27646e+06,819115,
134 "BM_SetInsert/1024/10",106365,17238.4,8421.53,4.74973e+06,1.18743e+06,
137 <a name="output-files" />
141 Write benchmark results to a file with the `--benchmark_out=<filename>` option
142 (or set `BENCHMARK_OUT`). Specify the output format with
143 `--benchmark_out_format={json|console|csv}` (or set
144 `BENCHMARK_OUT_FORMAT={json|console|csv}`). Note that the 'csv' reporter is
145 deprecated and the saved `.csv` file
146 [is not parsable](https://github.com/google/benchmark/issues/794) by csv
149 Specifying `--benchmark_out` does not suppress the console output.
151 <a name="running-benchmarks" />
153 ## Running Benchmarks
155 Benchmarks are executed by running the produced binaries. Benchmarks binaries,
156 by default, accept options that may be specified either through their command
157 line interface or by setting environment variables before execution. For every
158 `--option_flag=<value>` CLI switch, a corresponding environment variable
159 `OPTION_FLAG=<value>` exist and is used as default if set (CLI switches always
160 prevails). A complete list of CLI options is available running benchmarks
161 with the `--help` switch.
163 <a name="running-a-subset-of-benchmarks" />
165 ## Running a Subset of Benchmarks
167 The `--benchmark_filter=<regex>` option (or `BENCHMARK_FILTER=<regex>`
168 environment variable) can be used to only run the benchmarks that match
169 the specified `<regex>`. For example:
172 $ ./run_benchmarks.x --benchmark_filter=BM_memcpy/32
173 Run on (1 X 2300 MHz CPU )
175 Benchmark Time CPU Iterations
176 ----------------------------------------------------
177 BM_memcpy/32 11 ns 11 ns 79545455
178 BM_memcpy/32k 2181 ns 2185 ns 324074
179 BM_memcpy/32 12 ns 12 ns 54687500
180 BM_memcpy/32k 1834 ns 1837 ns 357143
183 <a name="result-comparison" />
187 It is possible to compare the benchmarking results.
188 See [Additional Tooling Documentation](tools.md)
190 <a name="extra-context" />
194 Sometimes it's useful to add extra context to the content printed before the
195 results. By default this section includes information about the CPU on which
196 the benchmarks are running. If you do want to add more context, you can use
197 the `benchmark_context` command line flag:
200 $ ./run_benchmarks --benchmark_context=pwd=`pwd`
201 Run on (1 x 2300 MHz CPU)
202 pwd: /home/user/benchmark/
203 Benchmark Time CPU Iterations
204 ----------------------------------------------------
205 BM_memcpy/32 11 ns 11 ns 79545455
206 BM_memcpy/32k 2181 ns 2185 ns 324074
209 You can get the same effect with the API:
212 benchmark::AddCustomContext("foo", "bar");
215 Note that attempts to add a second value with the same key will fail with an
218 <a name="runtime-and-reporting-considerations" />
220 ## Runtime and Reporting Considerations
222 When the benchmark binary is executed, each benchmark function is run serially.
223 The number of iterations to run is determined dynamically by running the
224 benchmark a few times and measuring the time taken and ensuring that the
225 ultimate result will be statistically stable. As such, faster benchmark
226 functions will be run for more iterations than slower benchmark functions, and
227 the number of iterations is thus reported.
229 In all cases, the number of iterations for which the benchmark is run is
230 governed by the amount of time the benchmark takes. Concretely, the number of
231 iterations is at least one, not more than 1e9, until CPU time is greater than
232 the minimum time, or the wallclock time is 5x minimum time. The minimum time is
233 set per benchmark by calling `MinTime` on the registered benchmark object.
235 Average timings are then reported over the iterations run. If multiple
236 repetitions are requested using the `--benchmark_repetitions` command-line
237 option, or at registration time, the benchmark function will be run several
238 times and statistical results across these repetitions will also be reported.
240 As well as the per-benchmark entries, a preamble in the report will include
241 information about the machine on which the benchmarks are run.
243 <a name="setup-teardown" />
247 Global setup/teardown specific to each benchmark can be done by
248 passing a callback to Setup/Teardown:
250 The setup/teardown callbacks will be invoked once for each benchmark.
251 If the benchmark is multi-threaded (will run in k threads), they will be invoked exactly once before
252 each run with k threads.
253 If the benchmark uses different size groups of threads, the above will be true for each size group.
258 static void DoSetup(const benchmark::State& state) {
261 static void DoTeardown(const benchmark::State& state) {
264 static void BM_func(benchmark::State& state) {...}
266 BENCHMARK(BM_func)->Arg(1)->Arg(3)->Threads(16)->Threads(32)->Setup(DoSetup)->Teardown(DoTeardown);
270 In this example, `DoSetup` and `DoTearDown` will be invoked 4 times each,
271 specifically, once for each of this family:
272 - BM_func_Arg_1_Threads_16, BM_func_Arg_1_Threads_32
273 - BM_func_Arg_3_Threads_16, BM_func_Arg_3_Threads_32
275 <a name="passing-arguments" />
279 Sometimes a family of benchmarks can be implemented with just one routine that
280 takes an extra argument to specify which one of the family of benchmarks to
281 run. For example, the following code defines a family of benchmarks for
282 measuring the speed of `memcpy()` calls of different lengths:
285 static void BM_memcpy(benchmark::State& state) {
286 char* src = new char[state.range(0)];
287 char* dst = new char[state.range(0)];
288 memset(src, 'x', state.range(0));
290 memcpy(dst, src, state.range(0));
291 state.SetBytesProcessed(int64_t(state.iterations()) *
292 int64_t(state.range(0)));
296 BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10);
299 The preceding code is quite repetitive, and can be replaced with the following
300 short-hand. The following invocation will pick a few appropriate arguments in
301 the specified range and will generate a benchmark for each such argument.
304 BENCHMARK(BM_memcpy)->Range(8, 8<<10);
307 By default the arguments in the range are generated in multiples of eight and
308 the command above selects [ 8, 64, 512, 4k, 8k ]. In the following code the
309 range multiplier is changed to multiples of two.
312 BENCHMARK(BM_memcpy)->RangeMultiplier(2)->Range(8, 8<<10);
315 Now arguments generated are [ 8, 16, 32, 64, 128, 256, 512, 1024, 2k, 4k, 8k ].
317 The preceding code shows a method of defining a sparse range. The following
318 example shows a method of defining a dense range. It is then used to benchmark
319 the performance of `std::vector` initialization for uniformly increasing sizes.
322 static void BM_DenseRange(benchmark::State& state) {
323 for(auto _ : state) {
324 std::vector<int> v(state.range(0), state.range(0));
325 benchmark::DoNotOptimize(v.data());
326 benchmark::ClobberMemory();
329 BENCHMARK(BM_DenseRange)->DenseRange(0, 1024, 128);
332 Now arguments generated are [ 0, 128, 256, 384, 512, 640, 768, 896, 1024 ].
334 You might have a benchmark that depends on two or more inputs. For example, the
335 following code defines a family of benchmarks for measuring the speed of set
339 static void BM_SetInsert(benchmark::State& state) {
341 for (auto _ : state) {
343 data = ConstructRandomSet(state.range(0));
344 state.ResumeTiming();
345 for (int j = 0; j < state.range(1); ++j)
346 data.insert(RandomNumber());
349 BENCHMARK(BM_SetInsert)
357 ->Args({8<<10, 512});
360 The preceding code is quite repetitive, and can be replaced with the following
361 short-hand. The following macro will pick a few appropriate arguments in the
362 product of the two specified ranges and will generate a benchmark for each such
367 BENCHMARK(BM_SetInsert)->Ranges({{1<<10, 8<<10}, {128, 512}});
371 Some benchmarks may require specific argument values that cannot be expressed
372 with `Ranges`. In this case, `ArgsProduct` offers the ability to generate a
373 benchmark input for each combination in the product of the supplied vectors.
377 BENCHMARK(BM_SetInsert)
378 ->ArgsProduct({{1<<10, 3<<10, 8<<10}, {20, 40, 60, 80}})
379 // would generate the same benchmark arguments as
380 BENCHMARK(BM_SetInsert)
396 For the most common scenarios, helper methods for creating a list of
397 integers for a given sparse or dense range are provided.
400 BENCHMARK(BM_SetInsert)
402 benchmark::CreateRange(8, 128, /*multi=*/2),
403 benchmark::CreateDenseRange(1, 4, /*step=*/1)
405 // would generate the same benchmark arguments as
406 BENCHMARK(BM_SetInsert)
408 {8, 16, 32, 64, 128},
413 For more complex patterns of inputs, passing a custom function to `Apply` allows
414 programmatic specification of an arbitrary set of arguments on which to run the
415 benchmark. The following example enumerates a dense range on one parameter,
416 and a sparse range on the second.
419 static void CustomArguments(benchmark::internal::Benchmark* b) {
420 for (int i = 0; i <= 10; ++i)
421 for (int j = 32; j <= 1024*1024; j *= 8)
424 BENCHMARK(BM_SetInsert)->Apply(CustomArguments);
427 ### Passing Arbitrary Arguments to a Benchmark
429 In C++11 it is possible to define a benchmark that takes an arbitrary number
430 of extra arguments. The `BENCHMARK_CAPTURE(func, test_case_name, ...args)`
431 macro creates a benchmark that invokes `func` with the `benchmark::State` as
432 the first argument followed by the specified `args...`.
433 The `test_case_name` is appended to the name of the benchmark and
434 should describe the values passed.
437 template <class ...ExtraArgs>
438 void BM_takes_args(benchmark::State& state, ExtraArgs&&... extra_args) {
441 // Registers a benchmark named "BM_takes_args/int_string_test" that passes
442 // the specified values to `extra_args`.
443 BENCHMARK_CAPTURE(BM_takes_args, int_string_test, 42, std::string("abc"));
446 Note that elements of `...args` may refer to global variables. Users should
447 avoid modifying global state inside of a benchmark.
449 <a name="asymptotic-complexity" />
451 ## Calculating Asymptotic Complexity (Big O)
453 Asymptotic complexity might be calculated for a family of benchmarks. The
454 following code will calculate the coefficient for the high-order term in the
455 running time and the normalized root-mean square error of string comparison.
458 static void BM_StringCompare(benchmark::State& state) {
459 std::string s1(state.range(0), '-');
460 std::string s2(state.range(0), '-');
461 for (auto _ : state) {
462 benchmark::DoNotOptimize(s1.compare(s2));
464 state.SetComplexityN(state.range(0));
466 BENCHMARK(BM_StringCompare)
467 ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity(benchmark::oN);
470 As shown in the following invocation, asymptotic complexity might also be
471 calculated automatically.
474 BENCHMARK(BM_StringCompare)
475 ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity();
478 The following code will specify asymptotic complexity with a lambda function,
479 that might be used to customize high-order term calculation.
482 BENCHMARK(BM_StringCompare)->RangeMultiplier(2)
483 ->Range(1<<10, 1<<18)->Complexity([](benchmark::IterationCount n)->double{return n; });
486 <a name="custom-benchmark-name" />
488 ## Custom Benchmark Name
490 You can change the benchmark's name as follows:
493 BENCHMARK(BM_memcpy)->Name("memcpy")->RangeMultiplier(2)->Range(8, 8<<10);
496 The invocation will execute the benchmark as before using `BM_memcpy` but changes
497 the prefix in the report to `memcpy`.
499 <a name="templated-benchmarks" />
501 ## Templated Benchmarks
503 This example produces and consumes messages of size `sizeof(v)` `range_x`
504 times. It also outputs throughput in the absence of multiprogramming.
507 template <class Q> void BM_Sequential(benchmark::State& state) {
509 typename Q::value_type v;
510 for (auto _ : state) {
511 for (int i = state.range(0); i--; )
513 for (int e = state.range(0); e--; )
516 // actually messages, not bytes:
517 state.SetBytesProcessed(
518 static_cast<int64_t>(state.iterations())*state.range(0));
521 BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue<int>)->Range(1<<0, 1<<10);
523 // C++11 or newer, you can use the BENCHMARK macro with template parameters:
524 BENCHMARK(BM_Sequential<WaitQueue<int>>)->Range(1<<0, 1<<10);
528 Three macros are provided for adding benchmark templates.
531 #ifdef BENCHMARK_HAS_CXX11
532 #define BENCHMARK(func<...>) // Takes any number of parameters.
534 #define BENCHMARK_TEMPLATE(func, arg1)
536 #define BENCHMARK_TEMPLATE1(func, arg1)
537 #define BENCHMARK_TEMPLATE2(func, arg1, arg2)
540 <a name="fixtures" />
544 Fixture tests are created by first defining a type that derives from
545 `::benchmark::Fixture` and then creating/registering the tests using the
548 * `BENCHMARK_F(ClassName, Method)`
549 * `BENCHMARK_DEFINE_F(ClassName, Method)`
550 * `BENCHMARK_REGISTER_F(ClassName, Method)`
555 class MyFixture : public benchmark::Fixture {
557 void SetUp(const ::benchmark::State& state) {
560 void TearDown(const ::benchmark::State& state) {
564 BENCHMARK_F(MyFixture, FooTest)(benchmark::State& st) {
570 BENCHMARK_DEFINE_F(MyFixture, BarTest)(benchmark::State& st) {
575 /* BarTest is NOT registered */
576 BENCHMARK_REGISTER_F(MyFixture, BarTest)->Threads(2);
577 /* BarTest is now registered */
580 ### Templated Fixtures
582 Also you can create templated fixture by using the following macros:
584 * `BENCHMARK_TEMPLATE_F(ClassName, Method, ...)`
585 * `BENCHMARK_TEMPLATE_DEFINE_F(ClassName, Method, ...)`
591 class MyFixture : public benchmark::Fixture {};
593 BENCHMARK_TEMPLATE_F(MyFixture, IntTest, int)(benchmark::State& st) {
599 BENCHMARK_TEMPLATE_DEFINE_F(MyFixture, DoubleTest, double)(benchmark::State& st) {
605 BENCHMARK_REGISTER_F(MyFixture, DoubleTest)->Threads(2);
608 <a name="custom-counters" />
612 You can add your own counters with user-defined names. The example below
613 will add columns "Foo", "Bar" and "Baz" in its output:
616 static void UserCountersExample1(benchmark::State& state) {
617 double numFoos = 0, numBars = 0, numBazs = 0;
618 for (auto _ : state) {
619 // ... count Foo,Bar,Baz events
621 state.counters["Foo"] = numFoos;
622 state.counters["Bar"] = numBars;
623 state.counters["Baz"] = numBazs;
627 The `state.counters` object is a `std::map` with `std::string` keys
628 and `Counter` values. The latter is a `double`-like class, via an implicit
629 conversion to `double&`. Thus you can use all of the standard arithmetic
630 assignment operators (`=,+=,-=,*=,/=`) to change the value of each counter.
632 In multithreaded benchmarks, each counter is set on the calling thread only.
633 When the benchmark finishes, the counters from each thread will be summed;
634 the resulting sum is the value which will be shown for the benchmark.
636 The `Counter` constructor accepts three parameters: the value as a `double`
637 ; a bit flag which allows you to show counters as rates, and/or as per-thread
638 iteration, and/or as per-thread averages, and/or iteration invariants,
639 and/or finally inverting the result; and a flag specifying the 'unit' - i.e.
640 is 1k a 1000 (default, `benchmark::Counter::OneK::kIs1000`), or 1024
641 (`benchmark::Counter::OneK::kIs1024`)?
644 // sets a simple counter
645 state.counters["Foo"] = numFoos;
647 // Set the counter as a rate. It will be presented divided
648 // by the duration of the benchmark.
649 // Meaning: per one second, how many 'foo's are processed?
650 state.counters["FooRate"] = Counter(numFoos, benchmark::Counter::kIsRate);
652 // Set the counter as a rate. It will be presented divided
653 // by the duration of the benchmark, and the result inverted.
654 // Meaning: how many seconds it takes to process one 'foo'?
655 state.counters["FooInvRate"] = Counter(numFoos, benchmark::Counter::kIsRate | benchmark::Counter::kInvert);
657 // Set the counter as a thread-average quantity. It will
658 // be presented divided by the number of threads.
659 state.counters["FooAvg"] = Counter(numFoos, benchmark::Counter::kAvgThreads);
661 // There's also a combined flag:
662 state.counters["FooAvgRate"] = Counter(numFoos,benchmark::Counter::kAvgThreadsRate);
664 // This says that we process with the rate of state.range(0) bytes every iteration:
665 state.counters["BytesProcessed"] = Counter(state.range(0), benchmark::Counter::kIsIterationInvariantRate, benchmark::Counter::OneK::kIs1024);
668 When you're compiling in C++11 mode or later you can use `insert()` with
669 `std::initializer_list`:
673 // With C++11, this can be done:
674 state.counters.insert({{"Foo", numFoos}, {"Bar", numBars}, {"Baz", numBazs}});
676 state.counters["Foo"] = numFoos;
677 state.counters["Bar"] = numBars;
678 state.counters["Baz"] = numBazs;
682 ### Counter Reporting
684 When using the console reporter, by default, user counters are printed at
685 the end after the table, the same way as ``bytes_processed`` and
686 ``items_processed``. This is best for cases in which there are few counters,
687 or where there are only a couple of lines per benchmark. Here's an example of
691 ------------------------------------------------------------------------------
692 Benchmark Time CPU Iterations UserCounters...
693 ------------------------------------------------------------------------------
694 BM_UserCounter/threads:8 2248 ns 10277 ns 68808 Bar=16 Bat=40 Baz=24 Foo=8
695 BM_UserCounter/threads:1 9797 ns 9788 ns 71523 Bar=2 Bat=5 Baz=3 Foo=1024m
696 BM_UserCounter/threads:2 4924 ns 9842 ns 71036 Bar=4 Bat=10 Baz=6 Foo=2
697 BM_UserCounter/threads:4 2589 ns 10284 ns 68012 Bar=8 Bat=20 Baz=12 Foo=4
698 BM_UserCounter/threads:8 2212 ns 10287 ns 68040 Bar=16 Bat=40 Baz=24 Foo=8
699 BM_UserCounter/threads:16 1782 ns 10278 ns 68144 Bar=32 Bat=80 Baz=48 Foo=16
700 BM_UserCounter/threads:32 1291 ns 10296 ns 68256 Bar=64 Bat=160 Baz=96 Foo=32
701 BM_UserCounter/threads:4 2615 ns 10307 ns 68040 Bar=8 Bat=20 Baz=12 Foo=4
702 BM_Factorial 26 ns 26 ns 26608979 40320
703 BM_Factorial/real_time 26 ns 26 ns 26587936 40320
704 BM_CalculatePiRange/1 16 ns 16 ns 45704255 0
705 BM_CalculatePiRange/8 73 ns 73 ns 9520927 3.28374
706 BM_CalculatePiRange/64 609 ns 609 ns 1140647 3.15746
707 BM_CalculatePiRange/512 4900 ns 4901 ns 142696 3.14355
710 If this doesn't suit you, you can print each counter as a table column by
711 passing the flag `--benchmark_counters_tabular=true` to the benchmark
712 application. This is best for cases in which there are a lot of counters, or
713 a lot of lines per individual benchmark. Note that this will trigger a
714 reprinting of the table header any time the counter set changes between
715 individual benchmarks. Here's an example of corresponding output when
716 `--benchmark_counters_tabular=true` is passed:
719 ---------------------------------------------------------------------------------------
720 Benchmark Time CPU Iterations Bar Bat Baz Foo
721 ---------------------------------------------------------------------------------------
722 BM_UserCounter/threads:8 2198 ns 9953 ns 70688 16 40 24 8
723 BM_UserCounter/threads:1 9504 ns 9504 ns 73787 2 5 3 1
724 BM_UserCounter/threads:2 4775 ns 9550 ns 72606 4 10 6 2
725 BM_UserCounter/threads:4 2508 ns 9951 ns 70332 8 20 12 4
726 BM_UserCounter/threads:8 2055 ns 9933 ns 70344 16 40 24 8
727 BM_UserCounter/threads:16 1610 ns 9946 ns 70720 32 80 48 16
728 BM_UserCounter/threads:32 1192 ns 9948 ns 70496 64 160 96 32
729 BM_UserCounter/threads:4 2506 ns 9949 ns 70332 8 20 12 4
730 --------------------------------------------------------------
731 Benchmark Time CPU Iterations
732 --------------------------------------------------------------
733 BM_Factorial 26 ns 26 ns 26392245 40320
734 BM_Factorial/real_time 26 ns 26 ns 26494107 40320
735 BM_CalculatePiRange/1 15 ns 15 ns 45571597 0
736 BM_CalculatePiRange/8 74 ns 74 ns 9450212 3.28374
737 BM_CalculatePiRange/64 595 ns 595 ns 1173901 3.15746
738 BM_CalculatePiRange/512 4752 ns 4752 ns 147380 3.14355
739 BM_CalculatePiRange/4k 37970 ns 37972 ns 18453 3.14184
740 BM_CalculatePiRange/32k 303733 ns 303744 ns 2305 3.14162
741 BM_CalculatePiRange/256k 2434095 ns 2434186 ns 288 3.1416
742 BM_CalculatePiRange/1024k 9721140 ns 9721413 ns 71 3.14159
743 BM_CalculatePi/threads:8 2255 ns 9943 ns 70936
746 Note above the additional header printed when the benchmark changes from
747 ``BM_UserCounter`` to ``BM_Factorial``. This is because ``BM_Factorial`` does
748 not have the same counter set as ``BM_UserCounter``.
750 <a name="multithreaded-benchmarks"/>
752 ## Multithreaded Benchmarks
754 In a multithreaded test (benchmark invoked by multiple threads simultaneously),
755 it is guaranteed that none of the threads will start until all have reached
756 the start of the benchmark loop, and all will have finished before any thread
757 exits the benchmark loop. (This behavior is also provided by the `KeepRunning()`
758 API) As such, any global setup or teardown can be wrapped in a check against the thread
762 static void BM_MultiThreaded(benchmark::State& state) {
763 if (state.thread_index() == 0) {
766 for (auto _ : state) {
767 // Run the test as normal.
769 if (state.thread_index() == 0) {
770 // Teardown code here.
773 BENCHMARK(BM_MultiThreaded)->Threads(2);
776 If the benchmarked code itself uses threads and you want to compare it to
777 single-threaded code, you may want to use real-time ("wallclock") measurements
778 for latency comparisons:
781 BENCHMARK(BM_test)->Range(8, 8<<10)->UseRealTime();
784 Without `UseRealTime`, CPU time is used by default.
786 <a name="cpu-timers" />
790 By default, the CPU timer only measures the time spent by the main thread.
791 If the benchmark itself uses threads internally, this measurement may not
792 be what you are looking for. Instead, there is a way to measure the total
793 CPU usage of the process, by all the threads.
798 static void MyMain(int size) {
799 #pragma omp parallel for
800 for(int i = 0; i < size; i++)
804 static void BM_OpenMP(benchmark::State& state) {
806 MyMain(state.range(0));
809 // Measure the time spent by the main thread, use it to decide for how long to
810 // run the benchmark loop. Depending on the internal implementation detail may
811 // measure to anywhere from near-zero (the overhead spent before/after work
812 // handoff to worker thread[s]) to the whole single-thread time.
813 BENCHMARK(BM_OpenMP)->Range(8, 8<<10);
815 // Measure the user-visible time, the wall clock (literally, the time that
816 // has passed on the clock on the wall), use it to decide for how long to
817 // run the benchmark loop. This will always be meaningful, an will match the
818 // time spent by the main thread in single-threaded case, in general decreasing
819 // with the number of internal threads doing the work.
820 BENCHMARK(BM_OpenMP)->Range(8, 8<<10)->UseRealTime();
822 // Measure the total CPU consumption, use it to decide for how long to
823 // run the benchmark loop. This will always measure to no less than the
824 // time spent by the main thread in single-threaded case.
825 BENCHMARK(BM_OpenMP)->Range(8, 8<<10)->MeasureProcessCPUTime();
827 // A mixture of the last two. Measure the total CPU consumption, but use the
828 // wall clock to decide for how long to run the benchmark loop.
829 BENCHMARK(BM_OpenMP)->Range(8, 8<<10)->MeasureProcessCPUTime()->UseRealTime();
832 ### Controlling Timers
834 Normally, the entire duration of the work loop (`for (auto _ : state) {}`)
835 is measured. But sometimes, it is necessary to do some work inside of
836 that loop, every iteration, but without counting that time to the benchmark time.
837 That is possible, although it is not recommended, since it has high overhead.
841 static void BM_SetInsert_With_Timer_Control(benchmark::State& state) {
843 for (auto _ : state) {
844 state.PauseTiming(); // Stop timers. They will not count until they are resumed.
845 data = ConstructRandomSet(state.range(0)); // Do something that should not be measured
846 state.ResumeTiming(); // And resume timers. They are now counting again.
847 // The rest will be measured.
848 for (int j = 0; j < state.range(1); ++j)
849 data.insert(RandomNumber());
852 BENCHMARK(BM_SetInsert_With_Timer_Control)->Ranges({{1<<10, 8<<10}, {128, 512}});
856 <a name="manual-timing" />
860 For benchmarking something for which neither CPU time nor real-time are
861 correct or accurate enough, completely manual timing is supported using
862 the `UseManualTime` function.
864 When `UseManualTime` is used, the benchmarked code must call
865 `SetIterationTime` once per iteration of the benchmark loop to
866 report the manually measured time.
868 An example use case for this is benchmarking GPU execution (e.g. OpenCL
869 or CUDA kernels, OpenGL or Vulkan or Direct3D draw calls), which cannot
870 be accurately measured using CPU time or real-time. Instead, they can be
871 measured accurately using a dedicated API, and these measurement results
872 can be reported back with `SetIterationTime`.
875 static void BM_ManualTiming(benchmark::State& state) {
876 int microseconds = state.range(0);
877 std::chrono::duration<double, std::micro> sleep_duration {
878 static_cast<double>(microseconds)
881 for (auto _ : state) {
882 auto start = std::chrono::high_resolution_clock::now();
883 // Simulate some useful workload with a sleep
884 std::this_thread::sleep_for(sleep_duration);
885 auto end = std::chrono::high_resolution_clock::now();
887 auto elapsed_seconds =
888 std::chrono::duration_cast<std::chrono::duration<double>>(
891 state.SetIterationTime(elapsed_seconds.count());
894 BENCHMARK(BM_ManualTiming)->Range(1, 1<<17)->UseManualTime();
897 <a name="setting-the-time-unit" />
899 ## Setting the Time Unit
901 If a benchmark runs a few milliseconds it may be hard to visually compare the
902 measured times, since the output data is given in nanoseconds per default. In
903 order to manually set the time unit, you can specify it manually:
906 BENCHMARK(BM_test)->Unit(benchmark::kMillisecond);
909 <a name="preventing-optimization" />
911 ## Preventing Optimization
913 To prevent a value or expression from being optimized away by the compiler
914 the `benchmark::DoNotOptimize(...)` and `benchmark::ClobberMemory()`
915 functions can be used.
918 static void BM_test(benchmark::State& state) {
919 for (auto _ : state) {
921 for (int i=0; i < 64; ++i) {
922 benchmark::DoNotOptimize(x += i);
928 `DoNotOptimize(<expr>)` forces the *result* of `<expr>` to be stored in either
929 memory or a register. For GNU based compilers it acts as read/write barrier
930 for global memory. More specifically it forces the compiler to flush pending
931 writes to memory and reload any other values as necessary.
933 Note that `DoNotOptimize(<expr>)` does not prevent optimizations on `<expr>`
934 in any way. `<expr>` may even be removed entirely when the result is already
938 /* Example 1: `<expr>` is removed entirely. */
939 int foo(int x) { return x + 42; }
940 while (...) DoNotOptimize(foo(0)); // Optimized to DoNotOptimize(42);
942 /* Example 2: Result of '<expr>' is only reused */
943 int bar(int) __attribute__((const));
944 while (...) DoNotOptimize(bar(0)); // Optimized to:
945 // int __result__ = bar(0);
946 // while (...) DoNotOptimize(__result__);
949 The second tool for preventing optimizations is `ClobberMemory()`. In essence
950 `ClobberMemory()` forces the compiler to perform all pending writes to global
951 memory. Memory managed by block scope objects must be "escaped" using
952 `DoNotOptimize(...)` before it can be clobbered. In the below example
953 `ClobberMemory()` prevents the call to `v.push_back(42)` from being optimized
957 static void BM_vector_push_back(benchmark::State& state) {
958 for (auto _ : state) {
961 benchmark::DoNotOptimize(v.data()); // Allow v.data() to be clobbered.
963 benchmark::ClobberMemory(); // Force 42 to be written to memory.
968 Note that `ClobberMemory()` is only available for GNU or MSVC based compilers.
970 <a name="reporting-statistics" />
972 ## Statistics: Reporting the Mean, Median and Standard Deviation / Coefficient of variation of Repeated Benchmarks
974 By default each benchmark is run once and that single result is reported.
975 However benchmarks are often noisy and a single result may not be representative
976 of the overall behavior. For this reason it's possible to repeatedly rerun the
979 The number of runs of each benchmark is specified globally by the
980 `--benchmark_repetitions` flag or on a per benchmark basis by calling
981 `Repetitions` on the registered benchmark object. When a benchmark is run more
982 than once the mean, median, standard deviation and coefficient of variation
983 of the runs will be reported.
985 Additionally the `--benchmark_report_aggregates_only={true|false}`,
986 `--benchmark_display_aggregates_only={true|false}` flags or
987 `ReportAggregatesOnly(bool)`, `DisplayAggregatesOnly(bool)` functions can be
988 used to change how repeated tests are reported. By default the result of each
989 repeated run is reported. When `report aggregates only` option is `true`,
990 only the aggregates (i.e. mean, median, standard deviation and coefficient
991 of variation, maybe complexity measurements if they were requested) of the runs
992 is reported, to both the reporters - standard output (console), and the file.
993 However when only the `display aggregates only` option is `true`,
994 only the aggregates are displayed in the standard output, while the file
995 output still contains everything.
996 Calling `ReportAggregatesOnly(bool)` / `DisplayAggregatesOnly(bool)` on a
997 registered benchmark object overrides the value of the appropriate flag for that
1000 <a name="custom-statistics" />
1002 ## Custom Statistics
1004 While having these aggregates is nice, this may not be enough for everyone.
1005 For example you may want to know what the largest observation is, e.g. because
1006 you have some real-time constraints. This is easy. The following code will
1007 specify a custom statistic to be calculated, defined by a lambda function.
1010 void BM_spin_empty(benchmark::State& state) {
1011 for (auto _ : state) {
1012 for (int x = 0; x < state.range(0); ++x) {
1013 benchmark::DoNotOptimize(x);
1018 BENCHMARK(BM_spin_empty)
1019 ->ComputeStatistics("max", [](const std::vector<double>& v) -> double {
1020 return *(std::max_element(std::begin(v), std::end(v)));
1025 While usually the statistics produce values in time units,
1026 you can also produce percentages:
1029 void BM_spin_empty(benchmark::State& state) {
1030 for (auto _ : state) {
1031 for (int x = 0; x < state.range(0); ++x) {
1032 benchmark::DoNotOptimize(x);
1037 BENCHMARK(BM_spin_empty)
1038 ->ComputeStatistics("ratio", [](const std::vector<double>& v) -> double {
1039 return std::begin(v) / std::end(v);
1040 }, benchmark::StatisticUnit::Percentage)
1044 <a name="using-register-benchmark" />
1046 ## Using RegisterBenchmark(name, fn, args...)
1048 The `RegisterBenchmark(name, func, args...)` function provides an alternative
1049 way to create and register benchmarks.
1050 `RegisterBenchmark(name, func, args...)` creates, registers, and returns a
1051 pointer to a new benchmark with the specified `name` that invokes
1052 `func(st, args...)` where `st` is a `benchmark::State` object.
1054 Unlike the `BENCHMARK` registration macros, which can only be used at the global
1055 scope, the `RegisterBenchmark` can be called anywhere. This allows for
1056 benchmark tests to be registered programmatically.
1058 Additionally `RegisterBenchmark` allows any callable object to be registered
1059 as a benchmark. Including capturing lambdas and function objects.
1063 auto BM_test = [](benchmark::State& st, auto Inputs) { /* ... */ };
1065 int main(int argc, char** argv) {
1066 for (auto& test_input : { /* ... */ })
1067 benchmark::RegisterBenchmark(test_input.name(), BM_test, test_input);
1068 benchmark::Initialize(&argc, argv);
1069 benchmark::RunSpecifiedBenchmarks();
1070 benchmark::Shutdown();
1074 <a name="exiting-with-an-error" />
1076 ## Exiting with an Error
1078 When errors caused by external influences, such as file I/O and network
1079 communication, occur within a benchmark the
1080 `State::SkipWithError(const char* msg)` function can be used to skip that run
1081 of benchmark and report the error. Note that only future iterations of the
1082 `KeepRunning()` are skipped. For the ranged-for version of the benchmark loop
1083 Users must explicitly exit the loop, otherwise all iterations will be performed.
1084 Users may explicitly return to exit the benchmark immediately.
1086 The `SkipWithError(...)` function may be used at any point within the benchmark,
1087 including before and after the benchmark loop. Moreover, if `SkipWithError(...)`
1088 has been used, it is not required to reach the benchmark loop and one may return
1089 from the benchmark function early.
1094 static void BM_test(benchmark::State& state) {
1095 auto resource = GetResource();
1096 if (!resource.good()) {
1097 state.SkipWithError("Resource is not good!");
1098 // KeepRunning() loop will not be entered.
1100 while (state.KeepRunning()) {
1101 auto data = resource.read_data();
1102 if (!resource.good()) {
1103 state.SkipWithError("Failed to read data!");
1104 break; // Needed to skip the rest of the iteration.
1110 static void BM_test_ranged_fo(benchmark::State & state) {
1111 auto resource = GetResource();
1112 if (!resource.good()) {
1113 state.SkipWithError("Resource is not good!");
1114 return; // Early return is allowed when SkipWithError() has been used.
1116 for (auto _ : state) {
1117 auto data = resource.read_data();
1118 if (!resource.good()) {
1119 state.SkipWithError("Failed to read data!");
1120 break; // REQUIRED to prevent all further iterations.
1126 <a name="a-faster-keep-running-loop" />
1128 ## A Faster KeepRunning Loop
1130 In C++11 mode, a ranged-based for loop should be used in preference to
1131 the `KeepRunning` loop for running the benchmarks. For example:
1134 static void BM_Fast(benchmark::State &state) {
1135 for (auto _ : state) {
1142 The reason the ranged-for loop is faster than using `KeepRunning`, is
1143 because `KeepRunning` requires a memory load and store of the iteration count
1144 ever iteration, whereas the ranged-for variant is able to keep the iteration count
1147 For example, an empty inner loop of using the ranged-based for method looks like:
1151 mov rbx, qword ptr [r14 + 104]
1152 call benchmark::State::StartKeepRunning()
1155 .LoopHeader: # =>This Inner Loop Header: Depth=1
1161 Compared to an empty `KeepRunning` loop, which looks like:
1164 .LoopHeader: # in Loop: Header=BB0_3 Depth=1
1165 cmp byte ptr [rbx], 1
1167 .LoopBody: # =>This Inner Loop Header: Depth=1
1168 mov rax, qword ptr [rbx + 8]
1170 mov qword ptr [rbx + 8], rcx
1171 cmp rax, qword ptr [rbx + 104]
1176 call benchmark::State::StartKeepRunning()
1181 Unless C++03 compatibility is required, the ranged-for variant of writing
1182 the benchmark loop should be preferred.
1184 <a name="disabling-cpu-frequency-scaling" />
1186 ## Disabling CPU Frequency Scaling
1188 If you see this error:
1191 ***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead.
1194 you might want to disable the CPU frequency scaling while running the benchmark:
1197 sudo cpupower frequency-set --governor performance
1199 sudo cpupower frequency-set --governor powersave