1# User Guide 2 3## Command Line 4 5[Output Formats](#output-formats) 6 7[Output Files](#output-files) 8 9[Running Benchmarks](#running-benchmarks) 10 11[Running a Subset of Benchmarks](#running-a-subset-of-benchmarks) 12 13[Result Comparison](#result-comparison) 14 15[Extra Context](#extra-context) 16 17## Library 18 19[Runtime and Reporting Considerations](#runtime-and-reporting-considerations) 20 21[Setup/Teardown](#setupteardown) 22 23[Passing Arguments](#passing-arguments) 24 25[Custom Benchmark Name](#custom-benchmark-name) 26 27[Calculating Asymptotic Complexity](#asymptotic-complexity) 28 29[Templated Benchmarks](#templated-benchmarks) 30 31[Fixtures](#fixtures) 32 33[Custom Counters](#custom-counters) 34 35[Multithreaded Benchmarks](#multithreaded-benchmarks) 36 37[CPU Timers](#cpu-timers) 38 39[Manual Timing](#manual-timing) 40 41[Setting the Time Unit](#setting-the-time-unit) 42 43[Random Interleaving](random_interleaving.md) 44 45[User-Requested Performance Counters](perf_counters.md) 46 47[Preventing Optimization](#preventing-optimization) 48 49[Reporting Statistics](#reporting-statistics) 50 51[Custom Statistics](#custom-statistics) 52 53[Using RegisterBenchmark](#using-register-benchmark) 54 55[Exiting with an Error](#exiting-with-an-error) 56 57[A Faster KeepRunning Loop](#a-faster-keep-running-loop) 58 59[Disabling CPU Frequency Scaling](#disabling-cpu-frequency-scaling) 60 61 62<a name="output-formats" /> 63 64## Output Formats 65 66The 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 69the format type. `console` is the default format. 70 71The Console format is intended to be a human readable format. By default 72the format generates color output. Context is output on stderr and the 73tabular data on stdout. Example tabular output looks like: 74 75``` 76Benchmark Time(ns) CPU(ns) Iterations 77---------------------------------------------------------------------- 78BM_SetInsert/1024/1 28928 29349 23853 133.097kB/s 33.2742k items/s 79BM_SetInsert/1024/8 32065 32913 21375 949.487kB/s 237.372k items/s 80BM_SetInsert/1024/10 33157 33648 21431 1.13369MB/s 290.225k items/s 81``` 82 83The JSON format outputs human readable json split into two top level attributes. 84The `context` attribute contains information about the run in general, including 85information about the CPU and the date. 86The `benchmarks` attribute contains a list of every benchmark run. Example json 87output looks like: 88 89```json 90{ 91 "context": { 92 "date": "2015/03/17-18:40:25", 93 "num_cpus": 40, 94 "mhz_per_cpu": 2801, 95 "cpu_scaling_enabled": false, 96 "build_type": "debug" 97 }, 98 "benchmarks": [ 99 { 100 "name": "BM_SetInsert/1024/1", 101 "iterations": 94877, 102 "real_time": 29275, 103 "cpu_time": 29836, 104 "bytes_per_second": 134066, 105 "items_per_second": 33516 106 }, 107 { 108 "name": "BM_SetInsert/1024/8", 109 "iterations": 21609, 110 "real_time": 32317, 111 "cpu_time": 32429, 112 "bytes_per_second": 986770, 113 "items_per_second": 246693 114 }, 115 { 116 "name": "BM_SetInsert/1024/10", 117 "iterations": 21393, 118 "real_time": 32724, 119 "cpu_time": 33355, 120 "bytes_per_second": 1199226, 121 "items_per_second": 299807 122 } 123 ] 124} 125``` 126 127The CSV format outputs comma-separated values. The `context` is output on stderr 128and the CSV itself on stdout. Example CSV output looks like: 129 130``` 131name,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, 135``` 136 137<a name="output-files" /> 138 139## Output Files 140 141Write 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 145deprecated and the saved `.csv` file 146[is not parsable](https://github.com/google/benchmark/issues/794) by csv 147parsers. 148 149Specifying `--benchmark_out` does not suppress the console output. 150 151<a name="running-benchmarks" /> 152 153## Running Benchmarks 154 155Benchmarks are executed by running the produced binaries. Benchmarks binaries, 156by default, accept options that may be specified either through their command 157line 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. 162 163<a name="running-a-subset-of-benchmarks" /> 164 165## Running a Subset of Benchmarks 166 167The `--benchmark_filter=<regex>` option (or `BENCHMARK_FILTER=<regex>` 168environment variable) can be used to only run the benchmarks that match 169the specified `<regex>`. For example: 170 171```bash 172$ ./run_benchmarks.x --benchmark_filter=BM_memcpy/32 173Run on (1 X 2300 MHz CPU ) 1742016-06-25 19:34:24 175Benchmark Time CPU Iterations 176---------------------------------------------------- 177BM_memcpy/32 11 ns 11 ns 79545455 178BM_memcpy/32k 2181 ns 2185 ns 324074 179BM_memcpy/32 12 ns 12 ns 54687500 180BM_memcpy/32k 1834 ns 1837 ns 357143 181``` 182 183<a name="result-comparison" /> 184 185## Result comparison 186 187It is possible to compare the benchmarking results. 188See [Additional Tooling Documentation](tools.md) 189 190<a name="extra-context" /> 191 192## Extra Context 193 194Sometimes it's useful to add extra context to the content printed before the 195results. By default this section includes information about the CPU on which 196the benchmarks are running. If you do want to add more context, you can use 197the `benchmark_context` command line flag: 198 199```bash 200$ ./run_benchmarks --benchmark_context=pwd=`pwd` 201Run on (1 x 2300 MHz CPU) 202pwd: /home/user/benchmark/ 203Benchmark Time CPU Iterations 204---------------------------------------------------- 205BM_memcpy/32 11 ns 11 ns 79545455 206BM_memcpy/32k 2181 ns 2185 ns 324074 207``` 208 209You can get the same effect with the API: 210 211```c++ 212 benchmark::AddCustomContext("foo", "bar"); 213``` 214 215Note that attempts to add a second value with the same key will fail with an 216error message. 217 218<a name="runtime-and-reporting-considerations" /> 219 220## Runtime and Reporting Considerations 221 222When the benchmark binary is executed, each benchmark function is run serially. 223The number of iterations to run is determined dynamically by running the 224benchmark a few times and measuring the time taken and ensuring that the 225ultimate result will be statistically stable. As such, faster benchmark 226functions will be run for more iterations than slower benchmark functions, and 227the number of iterations is thus reported. 228 229In all cases, the number of iterations for which the benchmark is run is 230governed by the amount of time the benchmark takes. Concretely, the number of 231iterations is at least one, not more than 1e9, until CPU time is greater than 232the minimum time, or the wallclock time is 5x minimum time. The minimum time is 233set per benchmark by calling `MinTime` on the registered benchmark object. 234 235Average timings are then reported over the iterations run. If multiple 236repetitions are requested using the `--benchmark_repetitions` command-line 237option, or at registration time, the benchmark function will be run several 238times and statistical results across these repetitions will also be reported. 239 240As well as the per-benchmark entries, a preamble in the report will include 241information about the machine on which the benchmarks are run. 242 243<a name="setup-teardown" /> 244 245## Setup/Teardown 246 247Global setup/teardown specific to each benchmark can be done by 248passing a callback to Setup/Teardown: 249 250The setup/teardown callbacks will be invoked once for each benchmark. 251If the benchmark is multi-threaded (will run in k threads), they will be invoked exactly once before 252each run with k threads. 253If the benchmark uses different size groups of threads, the above will be true for each size group. 254 255Eg., 256 257```c++ 258static void DoSetup(const benchmark::State& state) { 259} 260 261static void DoTeardown(const benchmark::State& state) { 262} 263 264static void BM_func(benchmark::State& state) {...} 265 266BENCHMARK(BM_func)->Arg(1)->Arg(3)->Threads(16)->Threads(32)->Setup(DoSetup)->Teardown(DoTeardown); 267 268``` 269 270In this example, `DoSetup` and `DoTearDown` will be invoked 4 times each, 271specifically, 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 274 275<a name="passing-arguments" /> 276 277## Passing Arguments 278 279Sometimes a family of benchmarks can be implemented with just one routine that 280takes an extra argument to specify which one of the family of benchmarks to 281run. For example, the following code defines a family of benchmarks for 282measuring the speed of `memcpy()` calls of different lengths: 283 284```c++ 285static 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)); 289 for (auto _ : state) 290 memcpy(dst, src, state.range(0)); 291 state.SetBytesProcessed(int64_t(state.iterations()) * 292 int64_t(state.range(0))); 293 delete[] src; 294 delete[] dst; 295} 296BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10); 297``` 298 299The preceding code is quite repetitive, and can be replaced with the following 300short-hand. The following invocation will pick a few appropriate arguments in 301the specified range and will generate a benchmark for each such argument. 302 303```c++ 304BENCHMARK(BM_memcpy)->Range(8, 8<<10); 305``` 306 307By default the arguments in the range are generated in multiples of eight and 308the command above selects [ 8, 64, 512, 4k, 8k ]. In the following code the 309range multiplier is changed to multiples of two. 310 311```c++ 312BENCHMARK(BM_memcpy)->RangeMultiplier(2)->Range(8, 8<<10); 313``` 314 315Now arguments generated are [ 8, 16, 32, 64, 128, 256, 512, 1024, 2k, 4k, 8k ]. 316 317The preceding code shows a method of defining a sparse range. The following 318example shows a method of defining a dense range. It is then used to benchmark 319the performance of `std::vector` initialization for uniformly increasing sizes. 320 321```c++ 322static 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(); 327 } 328} 329BENCHMARK(BM_DenseRange)->DenseRange(0, 1024, 128); 330``` 331 332Now arguments generated are [ 0, 128, 256, 384, 512, 640, 768, 896, 1024 ]. 333 334You might have a benchmark that depends on two or more inputs. For example, the 335following code defines a family of benchmarks for measuring the speed of set 336insertion. 337 338```c++ 339static void BM_SetInsert(benchmark::State& state) { 340 std::set<int> data; 341 for (auto _ : state) { 342 state.PauseTiming(); 343 data = ConstructRandomSet(state.range(0)); 344 state.ResumeTiming(); 345 for (int j = 0; j < state.range(1); ++j) 346 data.insert(RandomNumber()); 347 } 348} 349BENCHMARK(BM_SetInsert) 350 ->Args({1<<10, 128}) 351 ->Args({2<<10, 128}) 352 ->Args({4<<10, 128}) 353 ->Args({8<<10, 128}) 354 ->Args({1<<10, 512}) 355 ->Args({2<<10, 512}) 356 ->Args({4<<10, 512}) 357 ->Args({8<<10, 512}); 358``` 359 360The preceding code is quite repetitive, and can be replaced with the following 361short-hand. The following macro will pick a few appropriate arguments in the 362product of the two specified ranges and will generate a benchmark for each such 363pair. 364 365{% raw %} 366```c++ 367BENCHMARK(BM_SetInsert)->Ranges({{1<<10, 8<<10}, {128, 512}}); 368``` 369{% endraw %} 370 371Some benchmarks may require specific argument values that cannot be expressed 372with `Ranges`. In this case, `ArgsProduct` offers the ability to generate a 373benchmark input for each combination in the product of the supplied vectors. 374 375{% raw %} 376```c++ 377BENCHMARK(BM_SetInsert) 378 ->ArgsProduct({{1<<10, 3<<10, 8<<10}, {20, 40, 60, 80}}) 379// would generate the same benchmark arguments as 380BENCHMARK(BM_SetInsert) 381 ->Args({1<<10, 20}) 382 ->Args({3<<10, 20}) 383 ->Args({8<<10, 20}) 384 ->Args({3<<10, 40}) 385 ->Args({8<<10, 40}) 386 ->Args({1<<10, 40}) 387 ->Args({1<<10, 60}) 388 ->Args({3<<10, 60}) 389 ->Args({8<<10, 60}) 390 ->Args({1<<10, 80}) 391 ->Args({3<<10, 80}) 392 ->Args({8<<10, 80}); 393``` 394{% endraw %} 395 396For the most common scenarios, helper methods for creating a list of 397integers for a given sparse or dense range are provided. 398 399```c++ 400BENCHMARK(BM_SetInsert) 401 ->ArgsProduct({ 402 benchmark::CreateRange(8, 128, /*multi=*/2), 403 benchmark::CreateDenseRange(1, 4, /*step=*/1) 404 }) 405// would generate the same benchmark arguments as 406BENCHMARK(BM_SetInsert) 407 ->ArgsProduct({ 408 {8, 16, 32, 64, 128}, 409 {1, 2, 3, 4} 410 }); 411``` 412 413For more complex patterns of inputs, passing a custom function to `Apply` allows 414programmatic specification of an arbitrary set of arguments on which to run the 415benchmark. The following example enumerates a dense range on one parameter, 416and a sparse range on the second. 417 418```c++ 419static void CustomArguments(benchmark::internal::Benchmark* b) { 420 for (int i = 0; i <= 10; ++i) 421 for (int j = 32; j <= 1024*1024; j *= 8) 422 b->Args({i, j}); 423} 424BENCHMARK(BM_SetInsert)->Apply(CustomArguments); 425``` 426 427### Passing Arbitrary Arguments to a Benchmark 428 429In C++11 it is possible to define a benchmark that takes an arbitrary number 430of extra arguments. The `BENCHMARK_CAPTURE(func, test_case_name, ...args)` 431macro creates a benchmark that invokes `func` with the `benchmark::State` as 432the first argument followed by the specified `args...`. 433The `test_case_name` is appended to the name of the benchmark and 434should describe the values passed. 435 436```c++ 437template <class ...ExtraArgs> 438void BM_takes_args(benchmark::State& state, ExtraArgs&&... extra_args) { 439 [...] 440} 441// Registers a benchmark named "BM_takes_args/int_string_test" that passes 442// the specified values to `extra_args`. 443BENCHMARK_CAPTURE(BM_takes_args, int_string_test, 42, std::string("abc")); 444``` 445 446Note that elements of `...args` may refer to global variables. Users should 447avoid modifying global state inside of a benchmark. 448 449<a name="asymptotic-complexity" /> 450 451## Calculating Asymptotic Complexity (Big O) 452 453Asymptotic complexity might be calculated for a family of benchmarks. The 454following code will calculate the coefficient for the high-order term in the 455running time and the normalized root-mean square error of string comparison. 456 457```c++ 458static 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)); 463 } 464 state.SetComplexityN(state.range(0)); 465} 466BENCHMARK(BM_StringCompare) 467 ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity(benchmark::oN); 468``` 469 470As shown in the following invocation, asymptotic complexity might also be 471calculated automatically. 472 473```c++ 474BENCHMARK(BM_StringCompare) 475 ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity(); 476``` 477 478The following code will specify asymptotic complexity with a lambda function, 479that might be used to customize high-order term calculation. 480 481```c++ 482BENCHMARK(BM_StringCompare)->RangeMultiplier(2) 483 ->Range(1<<10, 1<<18)->Complexity([](benchmark::IterationCount n)->double{return n; }); 484``` 485 486<a name="custom-benchmark-name" /> 487 488## Custom Benchmark Name 489 490You can change the benchmark's name as follows: 491 492```c++ 493BENCHMARK(BM_memcpy)->Name("memcpy")->RangeMultiplier(2)->Range(8, 8<<10); 494``` 495 496The invocation will execute the benchmark as before using `BM_memcpy` but changes 497the prefix in the report to `memcpy`. 498 499<a name="templated-benchmarks" /> 500 501## Templated Benchmarks 502 503This example produces and consumes messages of size `sizeof(v)` `range_x` 504times. It also outputs throughput in the absence of multiprogramming. 505 506```c++ 507template <class Q> void BM_Sequential(benchmark::State& state) { 508 Q q; 509 typename Q::value_type v; 510 for (auto _ : state) { 511 for (int i = state.range(0); i--; ) 512 q.push(v); 513 for (int e = state.range(0); e--; ) 514 q.Wait(&v); 515 } 516 // actually messages, not bytes: 517 state.SetBytesProcessed( 518 static_cast<int64_t>(state.iterations())*state.range(0)); 519} 520// C++03 521BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue<int>)->Range(1<<0, 1<<10); 522 523// C++11 or newer, you can use the BENCHMARK macro with template parameters: 524BENCHMARK(BM_Sequential<WaitQueue<int>>)->Range(1<<0, 1<<10); 525 526``` 527 528Three macros are provided for adding benchmark templates. 529 530```c++ 531#ifdef BENCHMARK_HAS_CXX11 532#define BENCHMARK(func<...>) // Takes any number of parameters. 533#else // C++ < C++11 534#define BENCHMARK_TEMPLATE(func, arg1) 535#endif 536#define BENCHMARK_TEMPLATE1(func, arg1) 537#define BENCHMARK_TEMPLATE2(func, arg1, arg2) 538``` 539 540<a name="fixtures" /> 541 542## Fixtures 543 544Fixture tests are created by first defining a type that derives from 545`::benchmark::Fixture` and then creating/registering the tests using the 546following macros: 547 548* `BENCHMARK_F(ClassName, Method)` 549* `BENCHMARK_DEFINE_F(ClassName, Method)` 550* `BENCHMARK_REGISTER_F(ClassName, Method)` 551 552For Example: 553 554```c++ 555class MyFixture : public benchmark::Fixture { 556public: 557 void SetUp(const ::benchmark::State& state) { 558 } 559 560 void TearDown(const ::benchmark::State& state) { 561 } 562}; 563 564BENCHMARK_F(MyFixture, FooTest)(benchmark::State& st) { 565 for (auto _ : st) { 566 ... 567 } 568} 569 570BENCHMARK_DEFINE_F(MyFixture, BarTest)(benchmark::State& st) { 571 for (auto _ : st) { 572 ... 573 } 574} 575/* BarTest is NOT registered */ 576BENCHMARK_REGISTER_F(MyFixture, BarTest)->Threads(2); 577/* BarTest is now registered */ 578``` 579 580### Templated Fixtures 581 582Also you can create templated fixture by using the following macros: 583 584* `BENCHMARK_TEMPLATE_F(ClassName, Method, ...)` 585* `BENCHMARK_TEMPLATE_DEFINE_F(ClassName, Method, ...)` 586 587For example: 588 589```c++ 590template<typename T> 591class MyFixture : public benchmark::Fixture {}; 592 593BENCHMARK_TEMPLATE_F(MyFixture, IntTest, int)(benchmark::State& st) { 594 for (auto _ : st) { 595 ... 596 } 597} 598 599BENCHMARK_TEMPLATE_DEFINE_F(MyFixture, DoubleTest, double)(benchmark::State& st) { 600 for (auto _ : st) { 601 ... 602 } 603} 604 605BENCHMARK_REGISTER_F(MyFixture, DoubleTest)->Threads(2); 606``` 607 608<a name="custom-counters" /> 609 610## Custom Counters 611 612You can add your own counters with user-defined names. The example below 613will add columns "Foo", "Bar" and "Baz" in its output: 614 615```c++ 616static void UserCountersExample1(benchmark::State& state) { 617 double numFoos = 0, numBars = 0, numBazs = 0; 618 for (auto _ : state) { 619 // ... count Foo,Bar,Baz events 620 } 621 state.counters["Foo"] = numFoos; 622 state.counters["Bar"] = numBars; 623 state.counters["Baz"] = numBazs; 624} 625``` 626 627The `state.counters` object is a `std::map` with `std::string` keys 628and `Counter` values. The latter is a `double`-like class, via an implicit 629conversion to `double&`. Thus you can use all of the standard arithmetic 630assignment operators (`=,+=,-=,*=,/=`) to change the value of each counter. 631 632In multithreaded benchmarks, each counter is set on the calling thread only. 633When the benchmark finishes, the counters from each thread will be summed; 634the resulting sum is the value which will be shown for the benchmark. 635 636The `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 638iteration, and/or as per-thread averages, and/or iteration invariants, 639and/or finally inverting the result; and a flag specifying the 'unit' - i.e. 640is 1k a 1000 (default, `benchmark::Counter::OneK::kIs1000`), or 1024 641(`benchmark::Counter::OneK::kIs1024`)? 642 643```c++ 644 // sets a simple counter 645 state.counters["Foo"] = numFoos; 646 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); 651 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); 656 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); 660 661 // There's also a combined flag: 662 state.counters["FooAvgRate"] = Counter(numFoos,benchmark::Counter::kAvgThreadsRate); 663 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); 666``` 667 668When you're compiling in C++11 mode or later you can use `insert()` with 669`std::initializer_list`: 670 671{% raw %} 672```c++ 673 // With C++11, this can be done: 674 state.counters.insert({{"Foo", numFoos}, {"Bar", numBars}, {"Baz", numBazs}}); 675 // ... instead of: 676 state.counters["Foo"] = numFoos; 677 state.counters["Bar"] = numBars; 678 state.counters["Baz"] = numBazs; 679``` 680{% endraw %} 681 682### Counter Reporting 683 684When using the console reporter, by default, user counters are printed at 685the 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, 687or where there are only a couple of lines per benchmark. Here's an example of 688the default output: 689 690``` 691------------------------------------------------------------------------------ 692Benchmark Time CPU Iterations UserCounters... 693------------------------------------------------------------------------------ 694BM_UserCounter/threads:8 2248 ns 10277 ns 68808 Bar=16 Bat=40 Baz=24 Foo=8 695BM_UserCounter/threads:1 9797 ns 9788 ns 71523 Bar=2 Bat=5 Baz=3 Foo=1024m 696BM_UserCounter/threads:2 4924 ns 9842 ns 71036 Bar=4 Bat=10 Baz=6 Foo=2 697BM_UserCounter/threads:4 2589 ns 10284 ns 68012 Bar=8 Bat=20 Baz=12 Foo=4 698BM_UserCounter/threads:8 2212 ns 10287 ns 68040 Bar=16 Bat=40 Baz=24 Foo=8 699BM_UserCounter/threads:16 1782 ns 10278 ns 68144 Bar=32 Bat=80 Baz=48 Foo=16 700BM_UserCounter/threads:32 1291 ns 10296 ns 68256 Bar=64 Bat=160 Baz=96 Foo=32 701BM_UserCounter/threads:4 2615 ns 10307 ns 68040 Bar=8 Bat=20 Baz=12 Foo=4 702BM_Factorial 26 ns 26 ns 26608979 40320 703BM_Factorial/real_time 26 ns 26 ns 26587936 40320 704BM_CalculatePiRange/1 16 ns 16 ns 45704255 0 705BM_CalculatePiRange/8 73 ns 73 ns 9520927 3.28374 706BM_CalculatePiRange/64 609 ns 609 ns 1140647 3.15746 707BM_CalculatePiRange/512 4900 ns 4901 ns 142696 3.14355 708``` 709 710If this doesn't suit you, you can print each counter as a table column by 711passing the flag `--benchmark_counters_tabular=true` to the benchmark 712application. This is best for cases in which there are a lot of counters, or 713a lot of lines per individual benchmark. Note that this will trigger a 714reprinting of the table header any time the counter set changes between 715individual benchmarks. Here's an example of corresponding output when 716`--benchmark_counters_tabular=true` is passed: 717 718``` 719--------------------------------------------------------------------------------------- 720Benchmark Time CPU Iterations Bar Bat Baz Foo 721--------------------------------------------------------------------------------------- 722BM_UserCounter/threads:8 2198 ns 9953 ns 70688 16 40 24 8 723BM_UserCounter/threads:1 9504 ns 9504 ns 73787 2 5 3 1 724BM_UserCounter/threads:2 4775 ns 9550 ns 72606 4 10 6 2 725BM_UserCounter/threads:4 2508 ns 9951 ns 70332 8 20 12 4 726BM_UserCounter/threads:8 2055 ns 9933 ns 70344 16 40 24 8 727BM_UserCounter/threads:16 1610 ns 9946 ns 70720 32 80 48 16 728BM_UserCounter/threads:32 1192 ns 9948 ns 70496 64 160 96 32 729BM_UserCounter/threads:4 2506 ns 9949 ns 70332 8 20 12 4 730-------------------------------------------------------------- 731Benchmark Time CPU Iterations 732-------------------------------------------------------------- 733BM_Factorial 26 ns 26 ns 26392245 40320 734BM_Factorial/real_time 26 ns 26 ns 26494107 40320 735BM_CalculatePiRange/1 15 ns 15 ns 45571597 0 736BM_CalculatePiRange/8 74 ns 74 ns 9450212 3.28374 737BM_CalculatePiRange/64 595 ns 595 ns 1173901 3.15746 738BM_CalculatePiRange/512 4752 ns 4752 ns 147380 3.14355 739BM_CalculatePiRange/4k 37970 ns 37972 ns 18453 3.14184 740BM_CalculatePiRange/32k 303733 ns 303744 ns 2305 3.14162 741BM_CalculatePiRange/256k 2434095 ns 2434186 ns 288 3.1416 742BM_CalculatePiRange/1024k 9721140 ns 9721413 ns 71 3.14159 743BM_CalculatePi/threads:8 2255 ns 9943 ns 70936 744``` 745 746Note above the additional header printed when the benchmark changes from 747``BM_UserCounter`` to ``BM_Factorial``. This is because ``BM_Factorial`` does 748not have the same counter set as ``BM_UserCounter``. 749 750<a name="multithreaded-benchmarks"/> 751 752## Multithreaded Benchmarks 753 754In a multithreaded test (benchmark invoked by multiple threads simultaneously), 755it is guaranteed that none of the threads will start until all have reached 756the start of the benchmark loop, and all will have finished before any thread 757exits the benchmark loop. (This behavior is also provided by the `KeepRunning()` 758API) As such, any global setup or teardown can be wrapped in a check against the thread 759index: 760 761```c++ 762static void BM_MultiThreaded(benchmark::State& state) { 763 if (state.thread_index() == 0) { 764 // Setup code here. 765 } 766 for (auto _ : state) { 767 // Run the test as normal. 768 } 769 if (state.thread_index() == 0) { 770 // Teardown code here. 771 } 772} 773BENCHMARK(BM_MultiThreaded)->Threads(2); 774``` 775 776If the benchmarked code itself uses threads and you want to compare it to 777single-threaded code, you may want to use real-time ("wallclock") measurements 778for latency comparisons: 779 780```c++ 781BENCHMARK(BM_test)->Range(8, 8<<10)->UseRealTime(); 782``` 783 784Without `UseRealTime`, CPU time is used by default. 785 786<a name="cpu-timers" /> 787 788## CPU Timers 789 790By default, the CPU timer only measures the time spent by the main thread. 791If the benchmark itself uses threads internally, this measurement may not 792be what you are looking for. Instead, there is a way to measure the total 793CPU usage of the process, by all the threads. 794 795```c++ 796void callee(int i); 797 798static void MyMain(int size) { 799#pragma omp parallel for 800 for(int i = 0; i < size; i++) 801 callee(i); 802} 803 804static void BM_OpenMP(benchmark::State& state) { 805 for (auto _ : state) 806 MyMain(state.range(0)); 807} 808 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. 813BENCHMARK(BM_OpenMP)->Range(8, 8<<10); 814 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. 820BENCHMARK(BM_OpenMP)->Range(8, 8<<10)->UseRealTime(); 821 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. 825BENCHMARK(BM_OpenMP)->Range(8, 8<<10)->MeasureProcessCPUTime(); 826 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. 829BENCHMARK(BM_OpenMP)->Range(8, 8<<10)->MeasureProcessCPUTime()->UseRealTime(); 830``` 831 832### Controlling Timers 833 834Normally, the entire duration of the work loop (`for (auto _ : state) {}`) 835is measured. But sometimes, it is necessary to do some work inside of 836that loop, every iteration, but without counting that time to the benchmark time. 837That is possible, although it is not recommended, since it has high overhead. 838 839{% raw %} 840```c++ 841static void BM_SetInsert_With_Timer_Control(benchmark::State& state) { 842 std::set<int> data; 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()); 850 } 851} 852BENCHMARK(BM_SetInsert_With_Timer_Control)->Ranges({{1<<10, 8<<10}, {128, 512}}); 853``` 854{% endraw %} 855 856<a name="manual-timing" /> 857 858## Manual Timing 859 860For benchmarking something for which neither CPU time nor real-time are 861correct or accurate enough, completely manual timing is supported using 862the `UseManualTime` function. 863 864When `UseManualTime` is used, the benchmarked code must call 865`SetIterationTime` once per iteration of the benchmark loop to 866report the manually measured time. 867 868An example use case for this is benchmarking GPU execution (e.g. OpenCL 869or CUDA kernels, OpenGL or Vulkan or Direct3D draw calls), which cannot 870be accurately measured using CPU time or real-time. Instead, they can be 871measured accurately using a dedicated API, and these measurement results 872can be reported back with `SetIterationTime`. 873 874```c++ 875static 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) 879 }; 880 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(); 886 887 auto elapsed_seconds = 888 std::chrono::duration_cast<std::chrono::duration<double>>( 889 end - start); 890 891 state.SetIterationTime(elapsed_seconds.count()); 892 } 893} 894BENCHMARK(BM_ManualTiming)->Range(1, 1<<17)->UseManualTime(); 895``` 896 897<a name="setting-the-time-unit" /> 898 899## Setting the Time Unit 900 901If a benchmark runs a few milliseconds it may be hard to visually compare the 902measured times, since the output data is given in nanoseconds per default. In 903order to manually set the time unit, you can specify it manually: 904 905```c++ 906BENCHMARK(BM_test)->Unit(benchmark::kMillisecond); 907``` 908 909<a name="preventing-optimization" /> 910 911## Preventing Optimization 912 913To prevent a value or expression from being optimized away by the compiler 914the `benchmark::DoNotOptimize(...)` and `benchmark::ClobberMemory()` 915functions can be used. 916 917```c++ 918static void BM_test(benchmark::State& state) { 919 for (auto _ : state) { 920 int x = 0; 921 for (int i=0; i < 64; ++i) { 922 benchmark::DoNotOptimize(x += i); 923 } 924 } 925} 926``` 927 928`DoNotOptimize(<expr>)` forces the *result* of `<expr>` to be stored in either 929memory or a register. For GNU based compilers it acts as read/write barrier 930for global memory. More specifically it forces the compiler to flush pending 931writes to memory and reload any other values as necessary. 932 933Note that `DoNotOptimize(<expr>)` does not prevent optimizations on `<expr>` 934in any way. `<expr>` may even be removed entirely when the result is already 935known. For example: 936 937```c++ 938 /* Example 1: `<expr>` is removed entirely. */ 939 int foo(int x) { return x + 42; } 940 while (...) DoNotOptimize(foo(0)); // Optimized to DoNotOptimize(42); 941 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__); 947``` 948 949The second tool for preventing optimizations is `ClobberMemory()`. In essence 950`ClobberMemory()` forces the compiler to perform all pending writes to global 951memory. 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 954away. 955 956```c++ 957static void BM_vector_push_back(benchmark::State& state) { 958 for (auto _ : state) { 959 std::vector<int> v; 960 v.reserve(1); 961 benchmark::DoNotOptimize(v.data()); // Allow v.data() to be clobbered. 962 v.push_back(42); 963 benchmark::ClobberMemory(); // Force 42 to be written to memory. 964 } 965} 966``` 967 968Note that `ClobberMemory()` is only available for GNU or MSVC based compilers. 969 970<a name="reporting-statistics" /> 971 972## Statistics: Reporting the Mean, Median and Standard Deviation / Coefficient of variation of Repeated Benchmarks 973 974By default each benchmark is run once and that single result is reported. 975However benchmarks are often noisy and a single result may not be representative 976of the overall behavior. For this reason it's possible to repeatedly rerun the 977benchmark. 978 979The 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 982than once the mean, median, standard deviation and coefficient of variation 983of the runs will be reported. 984 985Additionally the `--benchmark_report_aggregates_only={true|false}`, 986`--benchmark_display_aggregates_only={true|false}` flags or 987`ReportAggregatesOnly(bool)`, `DisplayAggregatesOnly(bool)` functions can be 988used to change how repeated tests are reported. By default the result of each 989repeated run is reported. When `report aggregates only` option is `true`, 990only the aggregates (i.e. mean, median, standard deviation and coefficient 991of variation, maybe complexity measurements if they were requested) of the runs 992is reported, to both the reporters - standard output (console), and the file. 993However when only the `display aggregates only` option is `true`, 994only the aggregates are displayed in the standard output, while the file 995output still contains everything. 996Calling `ReportAggregatesOnly(bool)` / `DisplayAggregatesOnly(bool)` on a 997registered benchmark object overrides the value of the appropriate flag for that 998benchmark. 999 1000<a name="custom-statistics" /> 1001 1002## Custom Statistics 1003 1004While having these aggregates is nice, this may not be enough for everyone. 1005For example you may want to know what the largest observation is, e.g. because 1006you have some real-time constraints. This is easy. The following code will 1007specify a custom statistic to be calculated, defined by a lambda function. 1008 1009```c++ 1010void BM_spin_empty(benchmark::State& state) { 1011 for (auto _ : state) { 1012 for (int x = 0; x < state.range(0); ++x) { 1013 benchmark::DoNotOptimize(x); 1014 } 1015 } 1016} 1017 1018BENCHMARK(BM_spin_empty) 1019 ->ComputeStatistics("max", [](const std::vector<double>& v) -> double { 1020 return *(std::max_element(std::begin(v), std::end(v))); 1021 }) 1022 ->Arg(512); 1023``` 1024 1025While usually the statistics produce values in time units, 1026you can also produce percentages: 1027 1028```c++ 1029void BM_spin_empty(benchmark::State& state) { 1030 for (auto _ : state) { 1031 for (int x = 0; x < state.range(0); ++x) { 1032 benchmark::DoNotOptimize(x); 1033 } 1034 } 1035} 1036 1037BENCHMARK(BM_spin_empty) 1038 ->ComputeStatistics("ratio", [](const std::vector<double>& v) -> double { 1039 return std::begin(v) / std::end(v); 1040 }, benchmark::StatisticUnit::Percentage) 1041 ->Arg(512); 1042``` 1043 1044<a name="using-register-benchmark" /> 1045 1046## Using RegisterBenchmark(name, fn, args...) 1047 1048The `RegisterBenchmark(name, func, args...)` function provides an alternative 1049way to create and register benchmarks. 1050`RegisterBenchmark(name, func, args...)` creates, registers, and returns a 1051pointer to a new benchmark with the specified `name` that invokes 1052`func(st, args...)` where `st` is a `benchmark::State` object. 1053 1054Unlike the `BENCHMARK` registration macros, which can only be used at the global 1055scope, the `RegisterBenchmark` can be called anywhere. This allows for 1056benchmark tests to be registered programmatically. 1057 1058Additionally `RegisterBenchmark` allows any callable object to be registered 1059as a benchmark. Including capturing lambdas and function objects. 1060 1061For Example: 1062```c++ 1063auto BM_test = [](benchmark::State& st, auto Inputs) { /* ... */ }; 1064 1065int 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(); 1071} 1072``` 1073 1074<a name="exiting-with-an-error" /> 1075 1076## Exiting with an Error 1077 1078When errors caused by external influences, such as file I/O and network 1079communication, occur within a benchmark the 1080`State::SkipWithError(const char* msg)` function can be used to skip that run 1081of 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 1083Users must explicitly exit the loop, otherwise all iterations will be performed. 1084Users may explicitly return to exit the benchmark immediately. 1085 1086The `SkipWithError(...)` function may be used at any point within the benchmark, 1087including before and after the benchmark loop. Moreover, if `SkipWithError(...)` 1088has been used, it is not required to reach the benchmark loop and one may return 1089from the benchmark function early. 1090 1091For example: 1092 1093```c++ 1094static 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. 1099 } 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. 1105 } 1106 do_stuff(data); 1107 } 1108} 1109 1110static 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. 1115 } 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. 1121 } 1122 do_stuff(data); 1123 } 1124} 1125``` 1126<a name="a-faster-keep-running-loop" /> 1127 1128## A Faster KeepRunning Loop 1129 1130In C++11 mode, a ranged-based for loop should be used in preference to 1131the `KeepRunning` loop for running the benchmarks. For example: 1132 1133```c++ 1134static void BM_Fast(benchmark::State &state) { 1135 for (auto _ : state) { 1136 FastOperation(); 1137 } 1138} 1139BENCHMARK(BM_Fast); 1140``` 1141 1142The reason the ranged-for loop is faster than using `KeepRunning`, is 1143because `KeepRunning` requires a memory load and store of the iteration count 1144ever iteration, whereas the ranged-for variant is able to keep the iteration count 1145in a register. 1146 1147For example, an empty inner loop of using the ranged-based for method looks like: 1148 1149```asm 1150# Loop Init 1151 mov rbx, qword ptr [r14 + 104] 1152 call benchmark::State::StartKeepRunning() 1153 test rbx, rbx 1154 je .LoopEnd 1155.LoopHeader: # =>This Inner Loop Header: Depth=1 1156 add rbx, -1 1157 jne .LoopHeader 1158.LoopEnd: 1159``` 1160 1161Compared to an empty `KeepRunning` loop, which looks like: 1162 1163```asm 1164.LoopHeader: # in Loop: Header=BB0_3 Depth=1 1165 cmp byte ptr [rbx], 1 1166 jne .LoopInit 1167.LoopBody: # =>This Inner Loop Header: Depth=1 1168 mov rax, qword ptr [rbx + 8] 1169 lea rcx, [rax + 1] 1170 mov qword ptr [rbx + 8], rcx 1171 cmp rax, qword ptr [rbx + 104] 1172 jb .LoopHeader 1173 jmp .LoopEnd 1174.LoopInit: 1175 mov rdi, rbx 1176 call benchmark::State::StartKeepRunning() 1177 jmp .LoopBody 1178.LoopEnd: 1179``` 1180 1181Unless C++03 compatibility is required, the ranged-for variant of writing 1182the benchmark loop should be preferred. 1183 1184<a name="disabling-cpu-frequency-scaling" /> 1185 1186## Disabling CPU Frequency Scaling 1187 1188If you see this error: 1189 1190``` 1191***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead. 1192``` 1193 1194you might want to disable the CPU frequency scaling while running the benchmark: 1195 1196```bash 1197sudo cpupower frequency-set --governor performance 1198./mybench 1199sudo cpupower frequency-set --governor powersave 1200``` 1201