• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

cmake/H16-Feb-2021-435384

docs/H16-Feb-2021-390318

include/benchmark/H16-Feb-2021-1,468741

src/H03-May-2022-4,9943,535

test/H03-May-2022-3,4562,581

tools/H16-Feb-2021-1,134996

AUTHORSH A D16-Feb-20211.6 KiB4846

CONTRIBUTING.mdH A D16-Feb-20212.4 KiB5941

CONTRIBUTORSH A D16-Feb-20212.6 KiB6866

LICENSEH A D16-Feb-202111.1 KiB203169

README.LLVMH A D16-Feb-20212.2 KiB4035

README.mdH A D16-Feb-202133 KiB951780

WORKSPACEH A D16-Feb-2021284 86

appveyor.ymlH A D16-Feb-20211.4 KiB5742

mingw.pyH A D16-Feb-202110.1 KiB321281

releasing.mdH A D16-Feb-2021647 1715

README.LLVM

1LLVM notes
2----------
3
4This directory contains the Google Benchmark source code. Currently, the checked
5Benchmark library version is v1.4.1.
6
7This directory is under a different license than LLVM.
8
9Changes:
10
11* Bazel BUILD files are removed from the library
12* https://github.com/google/benchmark/commit/f85304e4e3a0e4e1bf15b91720df4a19e90b589f
13  is applied on top of the v1.4.1 to silence compiler warnings
14* https://github.com/google/benchmark/commit/505be96ab23056580a3a2315abba048f4428b04e
15  is applied to comply with the LLVM's required CMake version
16* https://github.com/google/benchmark/commit/f0901417c89d123474e6b91365029cfe32cf89dc
17  is applied to fix 32-bit build failure on macOS
18* https://github.com/google/benchmark/commit/52613079824ac58d06c070aa9fbbb186a5859e2c
19  is applied to fix cross compilation with MinGW headers
20* https://github.com/google/benchmark/commit/439d6b1c2a6da5cb6adc4c4dfc555af235722396
21  is applied to fix building with MinGW headers for ARM
22* https://github.com/google/benchmark/commit/a9b31c51b1ee7ec7b31438c647123c2cbac5d956
23  is applied to disable exceptions in Microsoft STL when exceptions are disabled
24* Disabled CMake get_git_version as it is meaningless for this in-tree build,
25  and hardcoded a null version
26* https://github.com/google/benchmark/commit/4abdfbb802d1b514703223f5f852ce4a507d32d2
27  is applied on top of v1.4.1 to add RISC-V timer support.
28* https://github.com/google/benchmark/commit/8e48105d465c586068dd8e248fe75a8971c6ba3a
29  is applied on top of v1.4.1 to fix cross-build from linux to windows via MinGW.
30* https://github.com/google/benchmark/commit/a77d5f70efaebe2b7e8c10134526a23a7ce7ef35
31  and
32  https://github.com/google/benchmark/commit/ecc1685340f58f7fe6b707036bc0bb1fccabb0c1
33  are applied on top of the previous cherrypick to fix timestamp-related inline
34  asm issues and 32-bit RISC-V build failures. The second cherrypicked commit
35  fixes formatting issues introduced by the preceding change.
36* https://github.com/google/benchmark/commit/ffe1342eb2faa7d2e7c35b4db2ccf99fab81ec20
37  is applied to add the CycleTimer implementation for M680x0
38* https://github.com/google/benchmark/commit/d9abf017632be4a00b92cf4289539b353fcea5d2
39  is applied to rename 'mftbl' to 'mftb'.
40

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