blob: 44466379ca87298fe7578c6586ee887f4c8fdc59 [file] [log] [blame] [view]
Dominic Hamond6f96ed2016-04-19 09:34:13 -07001# benchmark
Evgeny Safronov6f692462014-11-14 11:11:45 +04002[![Build Status](https://travis-ci.org/google/benchmark.svg?branch=master)](https://travis-ci.org/google/benchmark)
Dominic Hamon375e66c2015-05-11 12:34:03 -07003[![Build status](https://ci.appveyor.com/api/projects/status/u0qsyp7t1tk7cpxs/branch/master?svg=true)](https://ci.appveyor.com/project/google/benchmark/branch/master)
Dominic Hamond8c76052015-05-12 11:32:44 -07004[![Coverage Status](https://coveralls.io/repos/google/benchmark/badge.svg)](https://coveralls.io/r/google/benchmark)
Dominic Hamon373a7dd2014-01-07 17:04:19 -08005
Dominic Hamon01af2bc2013-12-20 14:51:56 -08006A library to support the benchmarking of functions, similar to unit-tests.
7
Dominic Hamon96446f22014-01-09 10:48:18 -08008Discussion group: https://groups.google.com/d/forum/benchmark-discuss
9
Dominic Hamon559c71d2015-10-13 12:02:08 -070010IRC channel: https://freenode.net #googlebenchmark
11
Eric Fiselier07ee1942016-09-03 00:19:37 -060012[Known issues and common problems](#known-issues)
Eric Fiselier61f570e2016-08-30 03:41:58 -060013
Eric83ac0862016-12-02 19:47:27 -070014[Additional Tooling Documentation](docs/tools.md)
15
Dominic Hamond6f96ed2016-04-19 09:34:13 -070016## Example usage
17### Basic usage
18Define a function that executes the code to be measured.
Dominic Hamon80162ca2013-12-20 14:53:25 -080019
Chris Seymour465cb092014-02-09 19:45:17 +000020```c++
21static void BM_StringCreation(benchmark::State& state) {
22 while (state.KeepRunning())
23 std::string empty_string;
24}
25// Register the function as a benchmark
26BENCHMARK(BM_StringCreation);
Dominic Hamon01af2bc2013-12-20 14:51:56 -080027
Chris Seymour465cb092014-02-09 19:45:17 +000028// Define another benchmark
29static void BM_StringCopy(benchmark::State& state) {
30 std::string x = "hello";
31 while (state.KeepRunning())
32 std::string copy(x);
33}
34BENCHMARK(BM_StringCopy);
Dominic Hamon01af2bc2013-12-20 14:51:56 -080035
Dominic Hamonbdf4a5f2015-03-12 21:56:45 -070036BENCHMARK_MAIN();
Chris Seymour465cb092014-02-09 19:45:17 +000037```
Dominic Hamon01af2bc2013-12-20 14:51:56 -080038
Dominic Hamond6f96ed2016-04-19 09:34:13 -070039### Passing arguments
40Sometimes a family of benchmarks can be implemented with just one routine that
41takes an extra argument to specify which one of the family of benchmarks to
42run. For example, the following code defines a family of benchmarks for
43measuring the speed of `memcpy()` calls of different lengths:
Dominic Hamon01af2bc2013-12-20 14:51:56 -080044
Chris Seymour465cb092014-02-09 19:45:17 +000045```c++
46static void BM_memcpy(benchmark::State& state) {
Marcin Kolnydfe02602016-08-04 21:30:14 +020047 char* src = new char[state.range(0)];
48 char* dst = new char[state.range(0)];
49 memset(src, 'x', state.range(0));
Paul Redmond0ce150e2014-07-23 13:36:58 -040050 while (state.KeepRunning())
Marcin Kolnydfe02602016-08-04 21:30:14 +020051 memcpy(dst, src, state.range(0));
Eli Benderskyf338ce72015-09-17 20:14:10 -070052 state.SetBytesProcessed(int64_t(state.iterations()) *
Marcin Kolnydfe02602016-08-04 21:30:14 +020053 int64_t(state.range(0)));
Chris Seymour465cb092014-02-09 19:45:17 +000054 delete[] src;
55 delete[] dst;
56}
57BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10);
58```
Dominic Hamon01af2bc2013-12-20 14:51:56 -080059
Dominic Hamond6f96ed2016-04-19 09:34:13 -070060The preceding code is quite repetitive, and can be replaced with the following
61short-hand. The following invocation will pick a few appropriate arguments in
62the specified range and will generate a benchmark for each such argument.
Dominic Hamon80162ca2013-12-20 14:53:25 -080063
Chris Seymour465cb092014-02-09 19:45:17 +000064```c++
65BENCHMARK(BM_memcpy)->Range(8, 8<<10);
66```
Dominic Hamon01af2bc2013-12-20 14:51:56 -080067
Dominic Hamon2440b752016-05-24 13:25:59 -070068By default the arguments in the range are generated in multiples of eight and
69the command above selects [ 8, 64, 512, 4k, 8k ]. In the following code the
70range multiplier is changed to multiples of two.
Ismael5812d542016-05-21 12:16:40 +020071
72```c++
73BENCHMARK(BM_memcpy)->RangeMultiplier(2)->Range(8, 8<<10);
74```
Ismael07efafb2016-05-21 16:34:12 +020075Now arguments generated are [ 8, 16, 32, 64, 128, 256, 512, 1024, 2k, 4k, 8k ].
Ismael5812d542016-05-21 12:16:40 +020076
Marcin Kolnydfe02602016-08-04 21:30:14 +020077You might have a benchmark that depends on two or more inputs. For example, the
Dominic Hamond6f96ed2016-04-19 09:34:13 -070078following code defines a family of benchmarks for measuring the speed of set
79insertion.
Dominic Hamon80162ca2013-12-20 14:53:25 -080080
Chris Seymour465cb092014-02-09 19:45:17 +000081```c++
82static void BM_SetInsert(benchmark::State& state) {
83 while (state.KeepRunning()) {
84 state.PauseTiming();
Marcin Kolnydfe02602016-08-04 21:30:14 +020085 std::set<int> data = ConstructRandomSet(state.range(0));
Chris Seymour465cb092014-02-09 19:45:17 +000086 state.ResumeTiming();
Marcin Kolnydfe02602016-08-04 21:30:14 +020087 for (int j = 0; j < state.range(1); ++j)
Chris Seymour465cb092014-02-09 19:45:17 +000088 data.insert(RandomNumber());
89 }
90}
91BENCHMARK(BM_SetInsert)
Marcin Kolnydfe02602016-08-04 21:30:14 +020092 ->Args({1<<10, 1})
93 ->Args({1<<10, 8})
94 ->Args({1<<10, 64})
95 ->Args({1<<10, 512})
96 ->Args({8<<10, 1})
97 ->Args({8<<10, 8})
98 ->Args({8<<10, 64})
99 ->Args({8<<10, 512});
Chris Seymour465cb092014-02-09 19:45:17 +0000100```
Dominic Hamon01af2bc2013-12-20 14:51:56 -0800101
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700102The preceding code is quite repetitive, and can be replaced with the following
103short-hand. The following macro will pick a few appropriate arguments in the
104product of the two specified ranges and will generate a benchmark for each such
105pair.
Dominic Hamon80162ca2013-12-20 14:53:25 -0800106
Chris Seymour465cb092014-02-09 19:45:17 +0000107```c++
Marcin Kolnydfe02602016-08-04 21:30:14 +0200108BENCHMARK(BM_SetInsert)->Ranges({{1<<10, 8<<10}, {1, 512}});
Chris Seymour465cb092014-02-09 19:45:17 +0000109```
Dominic Hamon01af2bc2013-12-20 14:51:56 -0800110
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700111For more complex patterns of inputs, passing a custom function to `Apply` allows
112programmatic specification of an arbitrary set of arguments on which to run the
113benchmark. The following example enumerates a dense range on one parameter,
Dominic Hamon01af2bc2013-12-20 14:51:56 -0800114and a sparse range on the second.
Dominic Hamon80162ca2013-12-20 14:53:25 -0800115
Chris Seymour465cb092014-02-09 19:45:17 +0000116```c++
Dominik Czarnotad2917bc2015-11-30 16:15:00 +0100117static void CustomArguments(benchmark::internal::Benchmark* b) {
Chris Seymour465cb092014-02-09 19:45:17 +0000118 for (int i = 0; i <= 10; ++i)
119 for (int j = 32; j <= 1024*1024; j *= 8)
Marcin Kolnydfe02602016-08-04 21:30:14 +0200120 b->Args({i, j});
Chris Seymour465cb092014-02-09 19:45:17 +0000121}
122BENCHMARK(BM_SetInsert)->Apply(CustomArguments);
123```
Dominic Hamon01af2bc2013-12-20 14:51:56 -0800124
Ismaeldc667d02016-05-21 12:40:27 +0200125### Calculate asymptotic complexity (Big O)
Dominic Hamon2440b752016-05-24 13:25:59 -0700126Asymptotic complexity might be calculated for a family of benchmarks. The
127following code will calculate the coefficient for the high-order term in the
128running time and the normalized root-mean square error of string comparison.
Ismaeldc667d02016-05-21 12:40:27 +0200129
130```c++
131static void BM_StringCompare(benchmark::State& state) {
Marcin Kolnydfe02602016-08-04 21:30:14 +0200132 std::string s1(state.range(0), '-');
133 std::string s2(state.range(0), '-');
Nickd1477972016-06-27 13:24:13 -0500134 while (state.KeepRunning()) {
Ismaeldc667d02016-05-21 12:40:27 +0200135 benchmark::DoNotOptimize(s1.compare(s2));
Nickd1477972016-06-27 13:24:13 -0500136 }
Marcin Kolnydfe02602016-08-04 21:30:14 +0200137 state.SetComplexityN(state.range(0));
Ismaeldc667d02016-05-21 12:40:27 +0200138}
139BENCHMARK(BM_StringCompare)
Dominic Hamon2440b752016-05-24 13:25:59 -0700140 ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity(benchmark::oN);
Ismaeldc667d02016-05-21 12:40:27 +0200141```
142
Dominic Hamon2440b752016-05-24 13:25:59 -0700143As shown in the following invocation, asymptotic complexity might also be
144calculated automatically.
Ismaeldc667d02016-05-21 12:40:27 +0200145
146```c++
147BENCHMARK(BM_StringCompare)
Ismael90a85082016-05-25 23:06:27 +0200148 ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity();
Ismaeldc667d02016-05-21 12:40:27 +0200149```
150
Ismael3ef63392016-06-02 20:58:14 +0200151The following code will specify asymptotic complexity with a lambda function,
152that might be used to customize high-order term calculation.
153
154```c++
155BENCHMARK(BM_StringCompare)->RangeMultiplier(2)
Ismael240ba4e2016-06-02 22:21:52 +0200156 ->Range(1<<10, 1<<18)->Complexity([](int n)->double{return n; });
Ismael3ef63392016-06-02 20:58:14 +0200157```
158
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700159### Templated benchmarks
160Templated benchmarks work the same way: This example produces and consumes
161messages of size `sizeof(v)` `range_x` times. It also outputs throughput in the
162absence of multiprogramming.
Dominic Hamon80162ca2013-12-20 14:53:25 -0800163
Chris Seymour465cb092014-02-09 19:45:17 +0000164```c++
165template <class Q> int BM_Sequential(benchmark::State& state) {
166 Q q;
167 typename Q::value_type v;
168 while (state.KeepRunning()) {
Marcin Kolnydfe02602016-08-04 21:30:14 +0200169 for (int i = state.range(0); i--; )
Chris Seymour465cb092014-02-09 19:45:17 +0000170 q.push(v);
Marcin Kolnydfe02602016-08-04 21:30:14 +0200171 for (int e = state.range(0); e--; )
Chris Seymour465cb092014-02-09 19:45:17 +0000172 q.Wait(&v);
173 }
174 // actually messages, not bytes:
175 state.SetBytesProcessed(
Marcin Kolnydfe02602016-08-04 21:30:14 +0200176 static_cast<int64_t>(state.iterations())*state.range(0));
Chris Seymour465cb092014-02-09 19:45:17 +0000177}
178BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue<int>)->Range(1<<0, 1<<10);
179```
Dominic Hamon01af2bc2013-12-20 14:51:56 -0800180
Eric Fiselierdaa8a672015-03-18 16:34:43 -0400181Three macros are provided for adding benchmark templates.
182
183```c++
184#if __cplusplus >= 201103L // C++11 and greater.
185#define BENCHMARK_TEMPLATE(func, ...) // Takes any number of parameters.
186#else // C++ < C++11
187#define BENCHMARK_TEMPLATE(func, arg1)
188#endif
189#define BENCHMARK_TEMPLATE1(func, arg1)
190#define BENCHMARK_TEMPLATE2(func, arg1, arg2)
191```
192
Eric238e5582016-05-27 13:37:10 -0600193## Passing arbitrary arguments to a benchmark
194In C++11 it is possible to define a benchmark that takes an arbitrary number
195of extra arguments. The `BENCHMARK_CAPTURE(func, test_case_name, ...args)`
196macro creates a benchmark that invokes `func` with the `benchmark::State` as
197the first argument followed by the specified `args...`.
198The `test_case_name` is appended to the name of the benchmark and
199should describe the values passed.
200
201```c++
202template <class ...ExtraArgs>`
203void BM_takes_args(benchmark::State& state, ExtraArgs&&... extra_args) {
204 [...]
205}
206// Registers a benchmark named "BM_takes_args/int_string_test` that passes
207// the specified values to `extra_args`.
208BENCHMARK_CAPTURE(BM_takes_args, int_string_test, 42, std::string("abc"));
209```
210Note that elements of `...args` may refer to global variables. Users should
211avoid modifying global state inside of a benchmark.
212
Eric5f5ca312016-08-02 17:22:46 -0600213## Using RegisterBenchmark(name, fn, args...)
214
215The `RegisterBenchmark(name, func, args...)` function provides an alternative
216way to create and register benchmarks.
217`RegisterBenchmark(name, func, args...)` creates, registers, and returns a
218pointer to a new benchmark with the specified `name` that invokes
219`func(st, args...)` where `st` is a `benchmark::State` object.
220
221Unlike the `BENCHMARK` registration macros, which can only be used at the global
222scope, the `RegisterBenchmark` can be called anywhere. This allows for
223benchmark tests to be registered programmatically.
224
225Additionally `RegisterBenchmark` allows any callable object to be registered
226as a benchmark. Including capturing lambdas and function objects. This
227allows the creation
228
229For Example:
230```c++
231auto BM_test = [](benchmark::State& st, auto Inputs) { /* ... */ };
232
233int main(int argc, char** argv) {
234 for (auto& test_input : { /* ... */ })
235 benchmark::RegisterBenchmark(test_input.name(), BM_test, test_input);
236 benchmark::Initialize(&argc, argv);
237 benchmark::RunSpecifiedBenchmarks();
238}
239```
240
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700241### Multithreaded benchmarks
Eli Benderskyc7ab1b92015-12-30 06:01:19 -0800242In a multithreaded test (benchmark invoked by multiple threads simultaneously),
243it is guaranteed that none of the threads will start until all have called
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700244`KeepRunning`, and all will have finished before KeepRunning returns false. As
245such, any global setup or teardown can be wrapped in a check against the thread
246index:
Dominic Hamon01af2bc2013-12-20 14:51:56 -0800247
Chris Seymour465cb092014-02-09 19:45:17 +0000248```c++
249static void BM_MultiThreaded(benchmark::State& state) {
250 if (state.thread_index == 0) {
251 // Setup code here.
252 }
253 while (state.KeepRunning()) {
254 // Run the test as normal.
255 }
256 if (state.thread_index == 0) {
257 // Teardown code here.
258 }
259}
260BENCHMARK(BM_MultiThreaded)->Threads(2);
Dominic Hamon4499e8e2015-11-05 09:53:08 -0800261```
Eric Fiseliere428b9e2015-03-27 16:35:46 -0400262
Eli Benderskyc7ab1b92015-12-30 06:01:19 -0800263If the benchmarked code itself uses threads and you want to compare it to
264single-threaded code, you may want to use real-time ("wallclock") measurements
265for latency comparisons:
266
267```c++
268BENCHMARK(BM_test)->Range(8, 8<<10)->UseRealTime();
269```
270
271Without `UseRealTime`, CPU time is used by default.
272
Jussi Knuuttilae253a282016-04-30 16:23:58 +0300273
274## Manual timing
275For benchmarking something for which neither CPU time nor real-time are
276correct or accurate enough, completely manual timing is supported using
277the `UseManualTime` function.
278
279When `UseManualTime` is used, the benchmarked code must call
280`SetIterationTime` once per iteration of the `KeepRunning` loop to
281report the manually measured time.
282
283An example use case for this is benchmarking GPU execution (e.g. OpenCL
284or CUDA kernels, OpenGL or Vulkan or Direct3D draw calls), which cannot
285be accurately measured using CPU time or real-time. Instead, they can be
286measured accurately using a dedicated API, and these measurement results
287can be reported back with `SetIterationTime`.
288
289```c++
290static void BM_ManualTiming(benchmark::State& state) {
Marcin Kolnydfe02602016-08-04 21:30:14 +0200291 int microseconds = state.range(0);
Jussi Knuuttilae253a282016-04-30 16:23:58 +0300292 std::chrono::duration<double, std::micro> sleep_duration {
293 static_cast<double>(microseconds)
294 };
295
296 while (state.KeepRunning()) {
297 auto start = std::chrono::high_resolution_clock::now();
298 // Simulate some useful workload with a sleep
299 std::this_thread::sleep_for(sleep_duration);
300 auto end = std::chrono::high_resolution_clock::now();
301
302 auto elapsed_seconds =
303 std::chrono::duration_cast<std::chrono::duration<double>>(
304 end - start);
305
306 state.SetIterationTime(elapsed_seconds.count());
307 }
308}
309BENCHMARK(BM_ManualTiming)->Range(1, 1<<17)->UseManualTime();
310```
311
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700312### Preventing optimisation
Eric Fiseliere428b9e2015-03-27 16:35:46 -0400313To prevent a value or expression from being optimized away by the compiler
Eric Fiselier7e40ff92016-07-11 14:58:50 -0600314the `benchmark::DoNotOptimize(...)` and `benchmark::ClobberMemory()`
315functions can be used.
Eric Fiseliere428b9e2015-03-27 16:35:46 -0400316
317```c++
318static void BM_test(benchmark::State& state) {
319 while (state.KeepRunning()) {
320 int x = 0;
321 for (int i=0; i < 64; ++i) {
322 benchmark::DoNotOptimize(x += i);
323 }
324 }
325}
Chris Seymour465cb092014-02-09 19:45:17 +0000326```
Dominic Hamonfd7d2882014-12-26 08:44:14 -0800327
Eric Fiselier7e40ff92016-07-11 14:58:50 -0600328`DoNotOptimize(<expr>)` forces the *result* of `<expr>` to be stored in either
329memory or a register. For GNU based compilers it acts as read/write barrier
330for global memory. More specifically it forces the compiler to flush pending
331writes to memory and reload any other values as necessary.
332
333Note that `DoNotOptimize(<expr>)` does not prevent optimizations on `<expr>`
334in any way. `<expr>` may even be removed entirely when the result is already
335known. For example:
336
337```c++
338 /* Example 1: `<expr>` is removed entirely. */
339 int foo(int x) { return x + 42; }
340 while (...) DoNotOptimize(foo(0)); // Optimized to DoNotOptimize(42);
341
342 /* Example 2: Result of '<expr>' is only reused */
343 int bar(int) __attribute__((const));
344 while (...) DoNotOptimize(bar(0)); // Optimized to:
345 // int __result__ = bar(0);
346 // while (...) DoNotOptimize(__result__);
347```
348
349The second tool for preventing optimizations is `ClobberMemory()`. In essence
350`ClobberMemory()` forces the compiler to perform all pending writes to global
351memory. Memory managed by block scope objects must be "escaped" using
352`DoNotOptimize(...)` before it can be clobbered. In the below example
353`ClobberMemory()` prevents the call to `v.push_back(42)` from being optimized
354away.
355
356```c++
357static void BM_vector_push_back(benchmark::State& state) {
358 while (state.KeepRunning()) {
359 std::vector<int> v;
360 v.reserve(1);
361 benchmark::DoNotOptimize(v.data()); // Allow v.data() to be clobbered.
362 v.push_back(42);
363 benchmark::ClobberMemory(); // Force 42 to be written to memory.
364 }
365}
366```
367
Ericf682f7e2017-03-10 18:47:39 -0700368Note that `ClobberMemory()` is only available for GNU or MSVC based compilers.
Eric Fiselier7e40ff92016-07-11 14:58:50 -0600369
Kai Wolff352c302016-04-29 21:42:21 +0200370### Set time unit manually
Kai Wolf0b4111c2016-03-28 21:32:11 +0200371If a benchmark runs a few milliseconds it may be hard to visually compare the
372measured times, since the output data is given in nanoseconds per default. In
373order to manually set the time unit, you can specify it manually:
374
375```c++
376BENCHMARK(BM_test)->Unit(benchmark::kMillisecond);
377```
378
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700379## Controlling number of iterations
380In all cases, the number of iterations for which the benchmark is run is
381governed by the amount of time the benchmark takes. Concretely, the number of
382iterations is at least one, not more than 1e9, until CPU time is greater than
383the minimum time, or the wallclock time is 5x minimum time. The minimum time is
384set as a flag `--benchmark_min_time` or per benchmark by calling `MinTime` on
385the registered benchmark object.
386
Eric Fiselier84bc4d72016-05-24 21:52:23 -0600387## Reporting the mean and standard devation by repeated benchmarks
388By default each benchmark is run once and that single result is reported.
389However benchmarks are often noisy and a single result may not be representative
390of the overall behavior. For this reason it's possible to repeatedly rerun the
391benchmark.
392
393The number of runs of each benchmark is specified globally by the
394`--benchmark_repetitions` flag or on a per benchmark basis by calling
395`Repetitions` on the registered benchmark object. When a benchmark is run
396more than once the mean and standard deviation of the runs will be reported.
397
Erica11fb692016-08-10 18:20:54 -0600398Additionally the `--benchmark_report_aggregates_only={true|false}` flag or
399`ReportAggregatesOnly(bool)` function can be used to change how repeated tests
400are reported. By default the result of each repeated run is reported. When this
401option is 'true' only the mean and standard deviation of the runs is reported.
402Calling `ReportAggregatesOnly(bool)` on a registered benchmark object overrides
403the value of the flag for that benchmark.
404
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700405## Fixtures
Eric Fiselier9ed538f2015-04-06 17:56:05 -0400406Fixture tests are created by
407first defining a type that derives from ::benchmark::Fixture and then
408creating/registering the tests using the following macros:
409
410* `BENCHMARK_F(ClassName, Method)`
411* `BENCHMARK_DEFINE_F(ClassName, Method)`
412* `BENCHMARK_REGISTER_F(ClassName, Method)`
413
414For Example:
415
416```c++
417class MyFixture : public benchmark::Fixture {};
418
419BENCHMARK_F(MyFixture, FooTest)(benchmark::State& st) {
420 while (st.KeepRunning()) {
421 ...
422 }
423}
424
425BENCHMARK_DEFINE_F(MyFixture, BarTest)(benchmark::State& st) {
426 while (st.KeepRunning()) {
427 ...
428 }
429}
430/* BarTest is NOT registered */
431BENCHMARK_REGISTER_F(MyFixture, BarTest)->Threads(2);
432/* BarTest is now registered */
433```
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400434
jpmaga9a66c82017-03-02 00:23:42 +0000435
436## User-defined counters
437
438You can add your own counters with user-defined names. The example below
439will add columns "Foo", "Bar" and "Baz" in its output:
440
441```c++
442static void UserCountersExample1(benchmark::State& state) {
443 double numFoos = 0, numBars = 0, numBazs = 0;
444 while (state.KeepRunning()) {
445 // ... count Foo,Bar,Baz events
446 }
447 state.counters["Foo"] = numFoos;
448 state.counters["Bar"] = numBars;
449 state.counters["Baz"] = numBazs;
450}
451```
452
453The `state.counters` object is a `std::map` with `std::string` keys
454and `Counter` values. The latter is a `double`-like class, via an implicit
455conversion to `double&`. Thus you can use all of the standard arithmetic
456assignment operators (`=,+=,-=,*=,/=`) to change the value of each counter.
457
458In multithreaded benchmarks, each counter is set on the calling thread only.
459When the benchmark finishes, the counters from each thread will be summed;
460the resulting sum is the value which will be shown for the benchmark.
461
462The `Counter` constructor accepts two parameters: the value as a `double`
463and a bit flag which allows you to show counters as rates and/or as
464per-thread averages:
465
466```c++
467 // sets a simple counter
468 state.counters["Foo"] = numFoos;
469
470 // Set the counter as a rate. It will be presented divided
471 // by the duration of the benchmark.
472 state.counters["FooRate"] = Counter(numFoos, benchmark::Counter::kIsRate);
473
474 // Set the counter as a thread-average quantity. It will
475 // be presented divided by the number of threads.
476 state.counters["FooAvg"] = Counter(numFoos, benchmark::Counter::kAvgThreads);
477
478 // There's also a combined flag:
479 state.counters["FooAvgRate"] = Counter(numFoos,benchmark::Counter::kAvgThreadsRate);
480```
481
482When you're compiling in C++11 mode or later you can use `insert()` with
483`std::initializer_list`:
484
485```c++
486 // With C++11, this can be done:
487 state.counters.insert({{"Foo", numFoos}, {"Bar", numBars}, {"Baz", numBazs}});
488 // ... instead of:
489 state.counters["Foo"] = numFoos;
490 state.counters["Bar"] = numBars;
491 state.counters["Baz"] = numBazs;
492```
493
Eric Fiselier90c9ab12016-05-23 20:35:09 -0600494## Exiting Benchmarks in Error
495
Eric Fiselier924b8ce2016-05-24 15:21:41 -0600496When errors caused by external influences, such as file I/O and network
497communication, occur within a benchmark the
498`State::SkipWithError(const char* msg)` function can be used to skip that run
499of benchmark and report the error. Note that only future iterations of the
500`KeepRunning()` are skipped. Users may explicitly return to exit the
501benchmark immediately.
Eric Fiselier90c9ab12016-05-23 20:35:09 -0600502
503The `SkipWithError(...)` function may be used at any point within the benchmark,
504including before and after the `KeepRunning()` loop.
505
506For example:
507
508```c++
509static void BM_test(benchmark::State& state) {
510 auto resource = GetResource();
511 if (!resource.good()) {
512 state.SkipWithError("Resource is not good!");
513 // KeepRunning() loop will not be entered.
514 }
515 while (state.KeepRunning()) {
516 auto data = resource.read_data();
517 if (!resource.good()) {
518 state.SkipWithError("Failed to read data!");
519 break; // Needed to skip the rest of the iteration.
520 }
521 do_stuff(data);
522 }
523}
524```
525
Eric Fiselier9c261682016-09-05 15:40:12 -0600526## Running a subset of the benchmarks
527
528The `--benchmark_filter=<regex>` option can be used to only run the benchmarks
529which match the specified `<regex>`. For example:
530
531```bash
532$ ./run_benchmarks.x --benchmark_filter=BM_memcpy/32
533Run on (1 X 2300 MHz CPU )
5342016-06-25 19:34:24
535Benchmark Time CPU Iterations
536----------------------------------------------------
537BM_memcpy/32 11 ns 11 ns 79545455
538BM_memcpy/32k 2181 ns 2185 ns 324074
539BM_memcpy/32 12 ns 12 ns 54687500
540BM_memcpy/32k 1834 ns 1837 ns 357143
541```
542
543
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700544## Output Formats
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400545The library supports multiple output formats. Use the
Eric Fiselier44128d82016-08-02 15:12:43 -0600546`--benchmark_format=<console|json|csv>` flag to set the format type. `console`
547is the default format.
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400548
Eric Fiselier44128d82016-08-02 15:12:43 -0600549The Console format is intended to be a human readable format. By default
Dominic Hamon99343962015-04-01 10:51:37 -0400550the format generates color output. Context is output on stderr and the
551tabular data on stdout. Example tabular output looks like:
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400552```
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400553Benchmark Time(ns) CPU(ns) Iterations
554----------------------------------------------------------------------
555BM_SetInsert/1024/1 28928 29349 23853 133.097kB/s 33.2742k items/s
556BM_SetInsert/1024/8 32065 32913 21375 949.487kB/s 237.372k items/s
557BM_SetInsert/1024/10 33157 33648 21431 1.13369MB/s 290.225k items/s
558```
559
560The JSON format outputs human readable json split into two top level attributes.
561The `context` attribute contains information about the run in general, including
562information about the CPU and the date.
563The `benchmarks` attribute contains a list of ever benchmark run. Example json
564output looks like:
jpmaga9a66c82017-03-02 00:23:42 +0000565```json
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400566{
567 "context": {
568 "date": "2015/03/17-18:40:25",
569 "num_cpus": 40,
570 "mhz_per_cpu": 2801,
571 "cpu_scaling_enabled": false,
572 "build_type": "debug"
573 },
574 "benchmarks": [
575 {
576 "name": "BM_SetInsert/1024/1",
577 "iterations": 94877,
578 "real_time": 29275,
579 "cpu_time": 29836,
580 "bytes_per_second": 134066,
581 "items_per_second": 33516
582 },
583 {
584 "name": "BM_SetInsert/1024/8",
585 "iterations": 21609,
586 "real_time": 32317,
587 "cpu_time": 32429,
588 "bytes_per_second": 986770,
589 "items_per_second": 246693
590 },
591 {
592 "name": "BM_SetInsert/1024/10",
593 "iterations": 21393,
594 "real_time": 32724,
595 "cpu_time": 33355,
596 "bytes_per_second": 1199226,
597 "items_per_second": 299807
598 }
599 ]
600}
601```
602
Dominic Hamon99343962015-04-01 10:51:37 -0400603The CSV format outputs comma-separated values. The `context` is output on stderr
604and the CSV itself on stdout. Example CSV output looks like:
605```
606name,iterations,real_time,cpu_time,bytes_per_second,items_per_second,label
607"BM_SetInsert/1024/1",65465,17890.7,8407.45,475768,118942,
608"BM_SetInsert/1024/8",116606,18810.1,9766.64,3.27646e+06,819115,
609"BM_SetInsert/1024/10",106365,17238.4,8421.53,4.74973e+06,1.18743e+06,
610```
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400611
Eric Fiselier44128d82016-08-02 15:12:43 -0600612## Output Files
613The library supports writing the output of the benchmark to a file specified
614by `--benchmark_out=<filename>`. The format of the output can be specified
615using `--benchmark_out_format={json|console|csv}`. Specifying
616`--benchmark_out` does not suppress the console output.
617
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700618## Debug vs Release
Dominic Hamon211f23e2016-02-14 09:28:10 -0800619By 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:
620
621```
622cmake -DCMAKE_BUILD_TYPE=Release
623```
624
625To enable link-time optimisation, use
626
627```
628cmake -DCMAKE_BUILD_TYPE=Release -DBENCHMARK_ENABLE_LTO=true
629```
630
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700631## Linking against the library
Ericde4ead72016-08-09 12:31:44 -0600632When using gcc, it is necessary to link against pthread to avoid runtime exceptions.
633This is due to how gcc implements std::thread.
Eric Fiselier98200352016-08-07 16:31:43 -0600634See [issue #67](https://github.com/google/benchmark/issues/67) for more details.
Ericde4ead72016-08-09 12:31:44 -0600635
636## Compiler Support
637
638Google Benchmark uses C++11 when building the library. As such we require
639a modern C++ toolchain, both compiler and standard library.
640
641The following minimum versions are strongly recommended build the library:
642
643* GCC 4.8
644* Clang 3.4
645* Visual Studio 2013
646
647Anything older *may* work.
648
649Note: Using the library and its headers in C++03 is supported. C++11 is only
650required to build the library.
Eric Fiselier61f570e2016-08-30 03:41:58 -0600651
652# Known Issues
653
654### Windows
655
656* Users must manually link `shlwapi.lib`. Failure to do so may result
Dominic Hamon62c68ba2016-09-23 12:44:22 -0700657in unresolved symbols.
658