NameDateSize

..30-May-202118

.clang-formatH A D29-May-202151

.gitignoreH A D29-May-2021652

.travis-libcxx-setup.shH A D29-May-20211.1 KiB

.travis.ymlH A D29-May-20216.6 KiB

.ycm_extra_conf.pyH A D29-May-20213.6 KiB

appveyor.ymlH A D29-May-20211.2 KiB

AUTHORSH A D29-May-20211.7 KiB

cmake/H30-May-202116

CMakeLists.txtH A D29-May-202110.6 KiB

CONTRIBUTING.mdH A D29-May-20212.4 KiB

CONTRIBUTORSH A D29-May-20212.7 KiB

docs/H30-May-20215

include/H30-May-20214

LICENSEH A D29-May-202111.1 KiB

mingw.pyH A D29-May-202110.1 KiB

README.LLVMH A D29-May-20211.4 KiB

README.mdH A D29-May-202135.8 KiB

releasing.mdH A D29-May-2021647

src/H30-May-202142

test/H30-May-202135

tools/H30-May-20216

WORKSPACEH A D29-May-2021284

README.LLVM

1LLVM notes
2----------
3
4This directory contains the Google Benchmark source code with some unnecessary
5files removed. Note that this directory is under a different license than
6libc++.
7
8Changes:
9* https://github.com/google/benchmark/commit/4abdfbb802d1b514703223f5f852ce4a507d32d2
10  is applied on top of
11  https://github.com/google/benchmark/commit/4528c76b718acc9b57956f63069c699ae21edcab
12  to add RISC-V timer support.
13* https://github.com/google/benchmark/commit/8e48105d465c586068dd8e248fe75a8971c6ba3a
14  is applied on top of
15  https://github.com/google/benchmark/commit/4528c76b718acc9b57956f63069c699ae21edcab
16  to fix cross-build from linux to windows via MinGW.
17* https://github.com/google/benchmark/commit/a77d5f70efaebe2b7e8c10134526a23a7ce7ef35
18  and
19  https://github.com/google/benchmark/commit/ecc1685340f58f7fe6b707036bc0bb1fccabb0c1
20  are applied on top of
21  https://github.com/google/benchmark/commit/8e48105d465c586068dd8e248fe75a8971c6ba3a
22  to fix timestamp-related inline asm issues and 32-bit RISC-V build failures.
23  The second cherrypicked commit fixes formatting issues introduced by the
24  preceding change.
25* https://github.com/google/benchmark/commit/ffe1342eb2faa7d2e7c35b4db2ccf99fab81ec20
26  is applied to add the CycleTimer implementation for M68k
27* https://github.com/google/benchmark/commit/d9abf017632be4a00b92cf4289539b353fcea5d2
28  is applied to rename 'mftbl' to 'mftb'.
29

README.md

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