You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1266 lines
43 KiB

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