blob: af994018d6fe7278f614bffe9c5eef1d8477b49b [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
Dominic Hamond6f96ed2016-04-19 09:34:13 -070014## Example usage
15### Basic usage
16Define a function that executes the code to be measured.
Dominic Hamon80162ca2013-12-20 14:53:25 -080017
Chris Seymour465cb092014-02-09 19:45:17 +000018```c++
19static void BM_StringCreation(benchmark::State& state) {
20 while (state.KeepRunning())
21 std::string empty_string;
22}
23// Register the function as a benchmark
24BENCHMARK(BM_StringCreation);
Dominic Hamon01af2bc2013-12-20 14:51:56 -080025
Chris Seymour465cb092014-02-09 19:45:17 +000026// Define another benchmark
27static void BM_StringCopy(benchmark::State& state) {
28 std::string x = "hello";
29 while (state.KeepRunning())
30 std::string copy(x);
31}
32BENCHMARK(BM_StringCopy);
Dominic Hamon01af2bc2013-12-20 14:51:56 -080033
Dominic Hamonbdf4a5f2015-03-12 21:56:45 -070034BENCHMARK_MAIN();
Chris Seymour465cb092014-02-09 19:45:17 +000035```
Dominic Hamon01af2bc2013-12-20 14:51:56 -080036
Dominic Hamond6f96ed2016-04-19 09:34:13 -070037### Passing arguments
38Sometimes a family of benchmarks can be implemented with just one routine that
39takes an extra argument to specify which one of the family of benchmarks to
40run. For example, the following code defines a family of benchmarks for
41measuring the speed of `memcpy()` calls of different lengths:
Dominic Hamon01af2bc2013-12-20 14:51:56 -080042
Chris Seymour465cb092014-02-09 19:45:17 +000043```c++
44static void BM_memcpy(benchmark::State& state) {
Marcin Kolnydfe02602016-08-04 21:30:14 +020045 char* src = new char[state.range(0)];
46 char* dst = new char[state.range(0)];
47 memset(src, 'x', state.range(0));
Paul Redmond0ce150e2014-07-23 13:36:58 -040048 while (state.KeepRunning())
Marcin Kolnydfe02602016-08-04 21:30:14 +020049 memcpy(dst, src, state.range(0));
Eli Benderskyf338ce72015-09-17 20:14:10 -070050 state.SetBytesProcessed(int64_t(state.iterations()) *
Marcin Kolnydfe02602016-08-04 21:30:14 +020051 int64_t(state.range(0)));
Chris Seymour465cb092014-02-09 19:45:17 +000052 delete[] src;
53 delete[] dst;
54}
55BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10);
56```
Dominic Hamon01af2bc2013-12-20 14:51:56 -080057
Dominic Hamond6f96ed2016-04-19 09:34:13 -070058The preceding code is quite repetitive, and can be replaced with the following
59short-hand. The following invocation will pick a few appropriate arguments in
60the specified range and will generate a benchmark for each such argument.
Dominic Hamon80162ca2013-12-20 14:53:25 -080061
Chris Seymour465cb092014-02-09 19:45:17 +000062```c++
63BENCHMARK(BM_memcpy)->Range(8, 8<<10);
64```
Dominic Hamon01af2bc2013-12-20 14:51:56 -080065
Dominic Hamon2440b752016-05-24 13:25:59 -070066By default the arguments in the range are generated in multiples of eight and
67the command above selects [ 8, 64, 512, 4k, 8k ]. In the following code the
68range multiplier is changed to multiples of two.
Ismael5812d542016-05-21 12:16:40 +020069
70```c++
71BENCHMARK(BM_memcpy)->RangeMultiplier(2)->Range(8, 8<<10);
72```
Ismael07efafb2016-05-21 16:34:12 +020073Now arguments generated are [ 8, 16, 32, 64, 128, 256, 512, 1024, 2k, 4k, 8k ].
Ismael5812d542016-05-21 12:16:40 +020074
Marcin Kolnydfe02602016-08-04 21:30:14 +020075You might have a benchmark that depends on two or more inputs. For example, the
Dominic Hamond6f96ed2016-04-19 09:34:13 -070076following code defines a family of benchmarks for measuring the speed of set
77insertion.
Dominic Hamon80162ca2013-12-20 14:53:25 -080078
Chris Seymour465cb092014-02-09 19:45:17 +000079```c++
80static void BM_SetInsert(benchmark::State& state) {
81 while (state.KeepRunning()) {
82 state.PauseTiming();
Marcin Kolnydfe02602016-08-04 21:30:14 +020083 std::set<int> data = ConstructRandomSet(state.range(0));
Chris Seymour465cb092014-02-09 19:45:17 +000084 state.ResumeTiming();
Marcin Kolnydfe02602016-08-04 21:30:14 +020085 for (int j = 0; j < state.range(1); ++j)
Chris Seymour465cb092014-02-09 19:45:17 +000086 data.insert(RandomNumber());
87 }
88}
89BENCHMARK(BM_SetInsert)
Marcin Kolnydfe02602016-08-04 21:30:14 +020090 ->Args({1<<10, 1})
91 ->Args({1<<10, 8})
92 ->Args({1<<10, 64})
93 ->Args({1<<10, 512})
94 ->Args({8<<10, 1})
95 ->Args({8<<10, 8})
96 ->Args({8<<10, 64})
97 ->Args({8<<10, 512});
Chris Seymour465cb092014-02-09 19:45:17 +000098```
Dominic Hamon01af2bc2013-12-20 14:51:56 -080099
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700100The preceding code is quite repetitive, and can be replaced with the following
101short-hand. The following macro will pick a few appropriate arguments in the
102product of the two specified ranges and will generate a benchmark for each such
103pair.
Dominic Hamon80162ca2013-12-20 14:53:25 -0800104
Chris Seymour465cb092014-02-09 19:45:17 +0000105```c++
Marcin Kolnydfe02602016-08-04 21:30:14 +0200106BENCHMARK(BM_SetInsert)->Ranges({{1<<10, 8<<10}, {1, 512}});
Chris Seymour465cb092014-02-09 19:45:17 +0000107```
Dominic Hamon01af2bc2013-12-20 14:51:56 -0800108
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700109For more complex patterns of inputs, passing a custom function to `Apply` allows
110programmatic specification of an arbitrary set of arguments on which to run the
111benchmark. The following example enumerates a dense range on one parameter,
Dominic Hamon01af2bc2013-12-20 14:51:56 -0800112and a sparse range on the second.
Dominic Hamon80162ca2013-12-20 14:53:25 -0800113
Chris Seymour465cb092014-02-09 19:45:17 +0000114```c++
Dominik Czarnotad2917bc2015-11-30 16:15:00 +0100115static void CustomArguments(benchmark::internal::Benchmark* b) {
Chris Seymour465cb092014-02-09 19:45:17 +0000116 for (int i = 0; i <= 10; ++i)
117 for (int j = 32; j <= 1024*1024; j *= 8)
Marcin Kolnydfe02602016-08-04 21:30:14 +0200118 b->Args({i, j});
Chris Seymour465cb092014-02-09 19:45:17 +0000119}
120BENCHMARK(BM_SetInsert)->Apply(CustomArguments);
121```
Dominic Hamon01af2bc2013-12-20 14:51:56 -0800122
Ismaeldc667d02016-05-21 12:40:27 +0200123### Calculate asymptotic complexity (Big O)
Dominic Hamon2440b752016-05-24 13:25:59 -0700124Asymptotic complexity might be calculated for a family of benchmarks. The
125following code will calculate the coefficient for the high-order term in the
126running time and the normalized root-mean square error of string comparison.
Ismaeldc667d02016-05-21 12:40:27 +0200127
128```c++
129static void BM_StringCompare(benchmark::State& state) {
Marcin Kolnydfe02602016-08-04 21:30:14 +0200130 std::string s1(state.range(0), '-');
131 std::string s2(state.range(0), '-');
Nickd1477972016-06-27 13:24:13 -0500132 while (state.KeepRunning()) {
Ismaeldc667d02016-05-21 12:40:27 +0200133 benchmark::DoNotOptimize(s1.compare(s2));
Nickd1477972016-06-27 13:24:13 -0500134 }
Marcin Kolnydfe02602016-08-04 21:30:14 +0200135 state.SetComplexityN(state.range(0));
Ismaeldc667d02016-05-21 12:40:27 +0200136}
137BENCHMARK(BM_StringCompare)
Dominic Hamon2440b752016-05-24 13:25:59 -0700138 ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity(benchmark::oN);
Ismaeldc667d02016-05-21 12:40:27 +0200139```
140
Dominic Hamon2440b752016-05-24 13:25:59 -0700141As shown in the following invocation, asymptotic complexity might also be
142calculated automatically.
Ismaeldc667d02016-05-21 12:40:27 +0200143
144```c++
145BENCHMARK(BM_StringCompare)
Ismael90a85082016-05-25 23:06:27 +0200146 ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity();
Ismaeldc667d02016-05-21 12:40:27 +0200147```
148
Ismael3ef63392016-06-02 20:58:14 +0200149The following code will specify asymptotic complexity with a lambda function,
150that might be used to customize high-order term calculation.
151
152```c++
153BENCHMARK(BM_StringCompare)->RangeMultiplier(2)
Ismael240ba4e2016-06-02 22:21:52 +0200154 ->Range(1<<10, 1<<18)->Complexity([](int n)->double{return n; });
Ismael3ef63392016-06-02 20:58:14 +0200155```
156
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700157### Templated benchmarks
158Templated benchmarks work the same way: This example produces and consumes
159messages of size `sizeof(v)` `range_x` times. It also outputs throughput in the
160absence of multiprogramming.
Dominic Hamon80162ca2013-12-20 14:53:25 -0800161
Chris Seymour465cb092014-02-09 19:45:17 +0000162```c++
163template <class Q> int BM_Sequential(benchmark::State& state) {
164 Q q;
165 typename Q::value_type v;
166 while (state.KeepRunning()) {
Marcin Kolnydfe02602016-08-04 21:30:14 +0200167 for (int i = state.range(0); i--; )
Chris Seymour465cb092014-02-09 19:45:17 +0000168 q.push(v);
Marcin Kolnydfe02602016-08-04 21:30:14 +0200169 for (int e = state.range(0); e--; )
Chris Seymour465cb092014-02-09 19:45:17 +0000170 q.Wait(&v);
171 }
172 // actually messages, not bytes:
173 state.SetBytesProcessed(
Marcin Kolnydfe02602016-08-04 21:30:14 +0200174 static_cast<int64_t>(state.iterations())*state.range(0));
Chris Seymour465cb092014-02-09 19:45:17 +0000175}
176BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue<int>)->Range(1<<0, 1<<10);
177```
Dominic Hamon01af2bc2013-12-20 14:51:56 -0800178
Eric Fiselierdaa8a672015-03-18 16:34:43 -0400179Three macros are provided for adding benchmark templates.
180
181```c++
182#if __cplusplus >= 201103L // C++11 and greater.
183#define BENCHMARK_TEMPLATE(func, ...) // Takes any number of parameters.
184#else // C++ < C++11
185#define BENCHMARK_TEMPLATE(func, arg1)
186#endif
187#define BENCHMARK_TEMPLATE1(func, arg1)
188#define BENCHMARK_TEMPLATE2(func, arg1, arg2)
189```
190
Eric238e5582016-05-27 13:37:10 -0600191## Passing arbitrary arguments to a benchmark
192In C++11 it is possible to define a benchmark that takes an arbitrary number
193of extra arguments. The `BENCHMARK_CAPTURE(func, test_case_name, ...args)`
194macro creates a benchmark that invokes `func` with the `benchmark::State` as
195the first argument followed by the specified `args...`.
196The `test_case_name` is appended to the name of the benchmark and
197should describe the values passed.
198
199```c++
200template <class ...ExtraArgs>`
201void BM_takes_args(benchmark::State& state, ExtraArgs&&... extra_args) {
202 [...]
203}
204// Registers a benchmark named "BM_takes_args/int_string_test` that passes
205// the specified values to `extra_args`.
206BENCHMARK_CAPTURE(BM_takes_args, int_string_test, 42, std::string("abc"));
207```
208Note that elements of `...args` may refer to global variables. Users should
209avoid modifying global state inside of a benchmark.
210
Eric5f5ca312016-08-02 17:22:46 -0600211## Using RegisterBenchmark(name, fn, args...)
212
213The `RegisterBenchmark(name, func, args...)` function provides an alternative
214way to create and register benchmarks.
215`RegisterBenchmark(name, func, args...)` creates, registers, and returns a
216pointer to a new benchmark with the specified `name` that invokes
217`func(st, args...)` where `st` is a `benchmark::State` object.
218
219Unlike the `BENCHMARK` registration macros, which can only be used at the global
220scope, the `RegisterBenchmark` can be called anywhere. This allows for
221benchmark tests to be registered programmatically.
222
223Additionally `RegisterBenchmark` allows any callable object to be registered
224as a benchmark. Including capturing lambdas and function objects. This
225allows the creation
226
227For Example:
228```c++
229auto BM_test = [](benchmark::State& st, auto Inputs) { /* ... */ };
230
231int main(int argc, char** argv) {
232 for (auto& test_input : { /* ... */ })
233 benchmark::RegisterBenchmark(test_input.name(), BM_test, test_input);
234 benchmark::Initialize(&argc, argv);
235 benchmark::RunSpecifiedBenchmarks();
236}
237```
238
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700239### Multithreaded benchmarks
Eli Benderskyc7ab1b92015-12-30 06:01:19 -0800240In a multithreaded test (benchmark invoked by multiple threads simultaneously),
241it is guaranteed that none of the threads will start until all have called
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700242`KeepRunning`, and all will have finished before KeepRunning returns false. As
243such, any global setup or teardown can be wrapped in a check against the thread
244index:
Dominic Hamon01af2bc2013-12-20 14:51:56 -0800245
Chris Seymour465cb092014-02-09 19:45:17 +0000246```c++
247static void BM_MultiThreaded(benchmark::State& state) {
248 if (state.thread_index == 0) {
249 // Setup code here.
250 }
251 while (state.KeepRunning()) {
252 // Run the test as normal.
253 }
254 if (state.thread_index == 0) {
255 // Teardown code here.
256 }
257}
258BENCHMARK(BM_MultiThreaded)->Threads(2);
Dominic Hamon4499e8e2015-11-05 09:53:08 -0800259```
Eric Fiseliere428b9e2015-03-27 16:35:46 -0400260
Eli Benderskyc7ab1b92015-12-30 06:01:19 -0800261If the benchmarked code itself uses threads and you want to compare it to
262single-threaded code, you may want to use real-time ("wallclock") measurements
263for latency comparisons:
264
265```c++
266BENCHMARK(BM_test)->Range(8, 8<<10)->UseRealTime();
267```
268
269Without `UseRealTime`, CPU time is used by default.
270
Jussi Knuuttilae253a282016-04-30 16:23:58 +0300271
272## Manual timing
273For benchmarking something for which neither CPU time nor real-time are
274correct or accurate enough, completely manual timing is supported using
275the `UseManualTime` function.
276
277When `UseManualTime` is used, the benchmarked code must call
278`SetIterationTime` once per iteration of the `KeepRunning` loop to
279report the manually measured time.
280
281An example use case for this is benchmarking GPU execution (e.g. OpenCL
282or CUDA kernels, OpenGL or Vulkan or Direct3D draw calls), which cannot
283be accurately measured using CPU time or real-time. Instead, they can be
284measured accurately using a dedicated API, and these measurement results
285can be reported back with `SetIterationTime`.
286
287```c++
288static void BM_ManualTiming(benchmark::State& state) {
Marcin Kolnydfe02602016-08-04 21:30:14 +0200289 int microseconds = state.range(0);
Jussi Knuuttilae253a282016-04-30 16:23:58 +0300290 std::chrono::duration<double, std::micro> sleep_duration {
291 static_cast<double>(microseconds)
292 };
293
294 while (state.KeepRunning()) {
295 auto start = std::chrono::high_resolution_clock::now();
296 // Simulate some useful workload with a sleep
297 std::this_thread::sleep_for(sleep_duration);
298 auto end = std::chrono::high_resolution_clock::now();
299
300 auto elapsed_seconds =
301 std::chrono::duration_cast<std::chrono::duration<double>>(
302 end - start);
303
304 state.SetIterationTime(elapsed_seconds.count());
305 }
306}
307BENCHMARK(BM_ManualTiming)->Range(1, 1<<17)->UseManualTime();
308```
309
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700310### Preventing optimisation
Eric Fiseliere428b9e2015-03-27 16:35:46 -0400311To prevent a value or expression from being optimized away by the compiler
Eric Fiselier7e40ff92016-07-11 14:58:50 -0600312the `benchmark::DoNotOptimize(...)` and `benchmark::ClobberMemory()`
313functions can be used.
Eric Fiseliere428b9e2015-03-27 16:35:46 -0400314
315```c++
316static void BM_test(benchmark::State& state) {
317 while (state.KeepRunning()) {
318 int x = 0;
319 for (int i=0; i < 64; ++i) {
320 benchmark::DoNotOptimize(x += i);
321 }
322 }
323}
Chris Seymour465cb092014-02-09 19:45:17 +0000324```
Dominic Hamonfd7d2882014-12-26 08:44:14 -0800325
Eric Fiselier7e40ff92016-07-11 14:58:50 -0600326`DoNotOptimize(<expr>)` forces the *result* of `<expr>` to be stored in either
327memory or a register. For GNU based compilers it acts as read/write barrier
328for global memory. More specifically it forces the compiler to flush pending
329writes to memory and reload any other values as necessary.
330
331Note that `DoNotOptimize(<expr>)` does not prevent optimizations on `<expr>`
332in any way. `<expr>` may even be removed entirely when the result is already
333known. For example:
334
335```c++
336 /* Example 1: `<expr>` is removed entirely. */
337 int foo(int x) { return x + 42; }
338 while (...) DoNotOptimize(foo(0)); // Optimized to DoNotOptimize(42);
339
340 /* Example 2: Result of '<expr>' is only reused */
341 int bar(int) __attribute__((const));
342 while (...) DoNotOptimize(bar(0)); // Optimized to:
343 // int __result__ = bar(0);
344 // while (...) DoNotOptimize(__result__);
345```
346
347The second tool for preventing optimizations is `ClobberMemory()`. In essence
348`ClobberMemory()` forces the compiler to perform all pending writes to global
349memory. Memory managed by block scope objects must be "escaped" using
350`DoNotOptimize(...)` before it can be clobbered. In the below example
351`ClobberMemory()` prevents the call to `v.push_back(42)` from being optimized
352away.
353
354```c++
355static void BM_vector_push_back(benchmark::State& state) {
356 while (state.KeepRunning()) {
357 std::vector<int> v;
358 v.reserve(1);
359 benchmark::DoNotOptimize(v.data()); // Allow v.data() to be clobbered.
360 v.push_back(42);
361 benchmark::ClobberMemory(); // Force 42 to be written to memory.
362 }
363}
364```
365
366Note that `ClobberMemory()` is only available for GNU based compilers.
367
Kai Wolff352c302016-04-29 21:42:21 +0200368### Set time unit manually
Kai Wolf0b4111c2016-03-28 21:32:11 +0200369If a benchmark runs a few milliseconds it may be hard to visually compare the
370measured times, since the output data is given in nanoseconds per default. In
371order to manually set the time unit, you can specify it manually:
372
373```c++
374BENCHMARK(BM_test)->Unit(benchmark::kMillisecond);
375```
376
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700377## Controlling number of iterations
378In all cases, the number of iterations for which the benchmark is run is
379governed by the amount of time the benchmark takes. Concretely, the number of
380iterations is at least one, not more than 1e9, until CPU time is greater than
381the minimum time, or the wallclock time is 5x minimum time. The minimum time is
382set as a flag `--benchmark_min_time` or per benchmark by calling `MinTime` on
383the registered benchmark object.
384
Eric Fiselier84bc4d72016-05-24 21:52:23 -0600385## Reporting the mean and standard devation by repeated benchmarks
386By default each benchmark is run once and that single result is reported.
387However benchmarks are often noisy and a single result may not be representative
388of the overall behavior. For this reason it's possible to repeatedly rerun the
389benchmark.
390
391The number of runs of each benchmark is specified globally by the
392`--benchmark_repetitions` flag or on a per benchmark basis by calling
393`Repetitions` on the registered benchmark object. When a benchmark is run
394more than once the mean and standard deviation of the runs will be reported.
395
Erica11fb692016-08-10 18:20:54 -0600396Additionally the `--benchmark_report_aggregates_only={true|false}` flag or
397`ReportAggregatesOnly(bool)` function can be used to change how repeated tests
398are reported. By default the result of each repeated run is reported. When this
399option is 'true' only the mean and standard deviation of the runs is reported.
400Calling `ReportAggregatesOnly(bool)` on a registered benchmark object overrides
401the value of the flag for that benchmark.
402
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700403## Fixtures
Eric Fiselier9ed538f2015-04-06 17:56:05 -0400404Fixture tests are created by
405first defining a type that derives from ::benchmark::Fixture and then
406creating/registering the tests using the following macros:
407
408* `BENCHMARK_F(ClassName, Method)`
409* `BENCHMARK_DEFINE_F(ClassName, Method)`
410* `BENCHMARK_REGISTER_F(ClassName, Method)`
411
412For Example:
413
414```c++
415class MyFixture : public benchmark::Fixture {};
416
417BENCHMARK_F(MyFixture, FooTest)(benchmark::State& st) {
418 while (st.KeepRunning()) {
419 ...
420 }
421}
422
423BENCHMARK_DEFINE_F(MyFixture, BarTest)(benchmark::State& st) {
424 while (st.KeepRunning()) {
425 ...
426 }
427}
428/* BarTest is NOT registered */
429BENCHMARK_REGISTER_F(MyFixture, BarTest)->Threads(2);
430/* BarTest is now registered */
431```
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400432
Eric Fiselier90c9ab12016-05-23 20:35:09 -0600433## Exiting Benchmarks in Error
434
Eric Fiselier924b8ce2016-05-24 15:21:41 -0600435When errors caused by external influences, such as file I/O and network
436communication, occur within a benchmark the
437`State::SkipWithError(const char* msg)` function can be used to skip that run
438of benchmark and report the error. Note that only future iterations of the
439`KeepRunning()` are skipped. Users may explicitly return to exit the
440benchmark immediately.
Eric Fiselier90c9ab12016-05-23 20:35:09 -0600441
442The `SkipWithError(...)` function may be used at any point within the benchmark,
443including before and after the `KeepRunning()` loop.
444
445For example:
446
447```c++
448static void BM_test(benchmark::State& state) {
449 auto resource = GetResource();
450 if (!resource.good()) {
451 state.SkipWithError("Resource is not good!");
452 // KeepRunning() loop will not be entered.
453 }
454 while (state.KeepRunning()) {
455 auto data = resource.read_data();
456 if (!resource.good()) {
457 state.SkipWithError("Failed to read data!");
458 break; // Needed to skip the rest of the iteration.
459 }
460 do_stuff(data);
461 }
462}
463```
464
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700465## Output Formats
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400466The library supports multiple output formats. Use the
Eric Fiselier44128d82016-08-02 15:12:43 -0600467`--benchmark_format=<console|json|csv>` flag to set the format type. `console`
468is the default format.
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400469
Eric Fiselier44128d82016-08-02 15:12:43 -0600470The Console format is intended to be a human readable format. By default
Dominic Hamon99343962015-04-01 10:51:37 -0400471the format generates color output. Context is output on stderr and the
472tabular data on stdout. Example tabular output looks like:
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400473```
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400474Benchmark Time(ns) CPU(ns) Iterations
475----------------------------------------------------------------------
476BM_SetInsert/1024/1 28928 29349 23853 133.097kB/s 33.2742k items/s
477BM_SetInsert/1024/8 32065 32913 21375 949.487kB/s 237.372k items/s
478BM_SetInsert/1024/10 33157 33648 21431 1.13369MB/s 290.225k items/s
479```
480
481The JSON format outputs human readable json split into two top level attributes.
482The `context` attribute contains information about the run in general, including
483information about the CPU and the date.
484The `benchmarks` attribute contains a list of ever benchmark run. Example json
485output looks like:
Arkady Shapkin8da907c2016-02-16 23:29:24 +0300486``` json
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400487{
488 "context": {
489 "date": "2015/03/17-18:40:25",
490 "num_cpus": 40,
491 "mhz_per_cpu": 2801,
492 "cpu_scaling_enabled": false,
493 "build_type": "debug"
494 },
495 "benchmarks": [
496 {
497 "name": "BM_SetInsert/1024/1",
498 "iterations": 94877,
499 "real_time": 29275,
500 "cpu_time": 29836,
501 "bytes_per_second": 134066,
502 "items_per_second": 33516
503 },
504 {
505 "name": "BM_SetInsert/1024/8",
506 "iterations": 21609,
507 "real_time": 32317,
508 "cpu_time": 32429,
509 "bytes_per_second": 986770,
510 "items_per_second": 246693
511 },
512 {
513 "name": "BM_SetInsert/1024/10",
514 "iterations": 21393,
515 "real_time": 32724,
516 "cpu_time": 33355,
517 "bytes_per_second": 1199226,
518 "items_per_second": 299807
519 }
520 ]
521}
522```
523
Dominic Hamon99343962015-04-01 10:51:37 -0400524The CSV format outputs comma-separated values. The `context` is output on stderr
525and the CSV itself on stdout. Example CSV output looks like:
526```
527name,iterations,real_time,cpu_time,bytes_per_second,items_per_second,label
528"BM_SetInsert/1024/1",65465,17890.7,8407.45,475768,118942,
529"BM_SetInsert/1024/8",116606,18810.1,9766.64,3.27646e+06,819115,
530"BM_SetInsert/1024/10",106365,17238.4,8421.53,4.74973e+06,1.18743e+06,
531```
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400532
Eric Fiselier44128d82016-08-02 15:12:43 -0600533## Output Files
534The library supports writing the output of the benchmark to a file specified
535by `--benchmark_out=<filename>`. The format of the output can be specified
536using `--benchmark_out_format={json|console|csv}`. Specifying
537`--benchmark_out` does not suppress the console output.
538
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700539## Debug vs Release
Dominic Hamon211f23e2016-02-14 09:28:10 -0800540By 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:
541
542```
543cmake -DCMAKE_BUILD_TYPE=Release
544```
545
546To enable link-time optimisation, use
547
548```
549cmake -DCMAKE_BUILD_TYPE=Release -DBENCHMARK_ENABLE_LTO=true
550```
551
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700552## Linking against the library
Ericde4ead72016-08-09 12:31:44 -0600553When using gcc, it is necessary to link against pthread to avoid runtime exceptions.
554This is due to how gcc implements std::thread.
Eric Fiselier98200352016-08-07 16:31:43 -0600555See [issue #67](https://github.com/google/benchmark/issues/67) for more details.
Ericde4ead72016-08-09 12:31:44 -0600556
557## Compiler Support
558
559Google Benchmark uses C++11 when building the library. As such we require
560a modern C++ toolchain, both compiler and standard library.
561
562The following minimum versions are strongly recommended build the library:
563
564* GCC 4.8
565* Clang 3.4
566* Visual Studio 2013
567
568Anything older *may* work.
569
570Note: Using the library and its headers in C++03 is supported. C++11 is only
571required to build the library.
Eric Fiselier61f570e2016-08-30 03:41:58 -0600572
573# Known Issues
574
575### Windows
576
577* Users must manually link `shlwapi.lib`. Failure to do so may result
578in resolved symbols.