blob: 2cfb70bd4578dd63b3dde54a54c11d929f183328 [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
368Note that `ClobberMemory()` is only available for GNU based compilers.
369
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
Eric Fiselier90c9ab12016-05-23 20:35:09 -0600435## Exiting Benchmarks in Error
436
Eric Fiselier924b8ce2016-05-24 15:21:41 -0600437When errors caused by external influences, such as file I/O and network
438communication, occur within a benchmark the
439`State::SkipWithError(const char* msg)` function can be used to skip that run
440of benchmark and report the error. Note that only future iterations of the
441`KeepRunning()` are skipped. Users may explicitly return to exit the
442benchmark immediately.
Eric Fiselier90c9ab12016-05-23 20:35:09 -0600443
444The `SkipWithError(...)` function may be used at any point within the benchmark,
445including before and after the `KeepRunning()` loop.
446
447For example:
448
449```c++
450static void BM_test(benchmark::State& state) {
451 auto resource = GetResource();
452 if (!resource.good()) {
453 state.SkipWithError("Resource is not good!");
454 // KeepRunning() loop will not be entered.
455 }
456 while (state.KeepRunning()) {
457 auto data = resource.read_data();
458 if (!resource.good()) {
459 state.SkipWithError("Failed to read data!");
460 break; // Needed to skip the rest of the iteration.
461 }
462 do_stuff(data);
463 }
464}
465```
466
Eric Fiselier9c261682016-09-05 15:40:12 -0600467## Running a subset of the benchmarks
468
469The `--benchmark_filter=<regex>` option can be used to only run the benchmarks
470which match the specified `<regex>`. For example:
471
472```bash
473$ ./run_benchmarks.x --benchmark_filter=BM_memcpy/32
474Run on (1 X 2300 MHz CPU )
4752016-06-25 19:34:24
476Benchmark Time CPU Iterations
477----------------------------------------------------
478BM_memcpy/32 11 ns 11 ns 79545455
479BM_memcpy/32k 2181 ns 2185 ns 324074
480BM_memcpy/32 12 ns 12 ns 54687500
481BM_memcpy/32k 1834 ns 1837 ns 357143
482```
483
484
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700485## Output Formats
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400486The library supports multiple output formats. Use the
Eric Fiselier44128d82016-08-02 15:12:43 -0600487`--benchmark_format=<console|json|csv>` flag to set the format type. `console`
488is the default format.
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400489
Eric Fiselier44128d82016-08-02 15:12:43 -0600490The Console format is intended to be a human readable format. By default
Dominic Hamon99343962015-04-01 10:51:37 -0400491the format generates color output. Context is output on stderr and the
492tabular data on stdout. Example tabular output looks like:
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400493```
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400494Benchmark Time(ns) CPU(ns) Iterations
495----------------------------------------------------------------------
496BM_SetInsert/1024/1 28928 29349 23853 133.097kB/s 33.2742k items/s
497BM_SetInsert/1024/8 32065 32913 21375 949.487kB/s 237.372k items/s
498BM_SetInsert/1024/10 33157 33648 21431 1.13369MB/s 290.225k items/s
499```
500
501The JSON format outputs human readable json split into two top level attributes.
502The `context` attribute contains information about the run in general, including
503information about the CPU and the date.
504The `benchmarks` attribute contains a list of ever benchmark run. Example json
505output looks like:
Arkady Shapkin8da907c2016-02-16 23:29:24 +0300506``` json
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400507{
508 "context": {
509 "date": "2015/03/17-18:40:25",
510 "num_cpus": 40,
511 "mhz_per_cpu": 2801,
512 "cpu_scaling_enabled": false,
513 "build_type": "debug"
514 },
515 "benchmarks": [
516 {
517 "name": "BM_SetInsert/1024/1",
518 "iterations": 94877,
519 "real_time": 29275,
520 "cpu_time": 29836,
521 "bytes_per_second": 134066,
522 "items_per_second": 33516
523 },
524 {
525 "name": "BM_SetInsert/1024/8",
526 "iterations": 21609,
527 "real_time": 32317,
528 "cpu_time": 32429,
529 "bytes_per_second": 986770,
530 "items_per_second": 246693
531 },
532 {
533 "name": "BM_SetInsert/1024/10",
534 "iterations": 21393,
535 "real_time": 32724,
536 "cpu_time": 33355,
537 "bytes_per_second": 1199226,
538 "items_per_second": 299807
539 }
540 ]
541}
542```
543
Dominic Hamon99343962015-04-01 10:51:37 -0400544The CSV format outputs comma-separated values. The `context` is output on stderr
545and the CSV itself on stdout. Example CSV output looks like:
546```
547name,iterations,real_time,cpu_time,bytes_per_second,items_per_second,label
548"BM_SetInsert/1024/1",65465,17890.7,8407.45,475768,118942,
549"BM_SetInsert/1024/8",116606,18810.1,9766.64,3.27646e+06,819115,
550"BM_SetInsert/1024/10",106365,17238.4,8421.53,4.74973e+06,1.18743e+06,
551```
Eric Fiselierffb67dc2015-03-17 18:42:41 -0400552
Eric Fiselier44128d82016-08-02 15:12:43 -0600553## Output Files
554The library supports writing the output of the benchmark to a file specified
555by `--benchmark_out=<filename>`. The format of the output can be specified
556using `--benchmark_out_format={json|console|csv}`. Specifying
557`--benchmark_out` does not suppress the console output.
558
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700559## Debug vs Release
Dominic Hamon211f23e2016-02-14 09:28:10 -0800560By 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:
561
562```
563cmake -DCMAKE_BUILD_TYPE=Release
564```
565
566To enable link-time optimisation, use
567
568```
569cmake -DCMAKE_BUILD_TYPE=Release -DBENCHMARK_ENABLE_LTO=true
570```
571
Dominic Hamond6f96ed2016-04-19 09:34:13 -0700572## Linking against the library
Ericde4ead72016-08-09 12:31:44 -0600573When using gcc, it is necessary to link against pthread to avoid runtime exceptions.
574This is due to how gcc implements std::thread.
Eric Fiselier98200352016-08-07 16:31:43 -0600575See [issue #67](https://github.com/google/benchmark/issues/67) for more details.
Ericde4ead72016-08-09 12:31:44 -0600576
577## Compiler Support
578
579Google Benchmark uses C++11 when building the library. As such we require
580a modern C++ toolchain, both compiler and standard library.
581
582The following minimum versions are strongly recommended build the library:
583
584* GCC 4.8
585* Clang 3.4
586* Visual Studio 2013
587
588Anything older *may* work.
589
590Note: Using the library and its headers in C++03 is supported. C++11 is only
591required to build the library.
Eric Fiselier61f570e2016-08-30 03:41:58 -0600592
593# Known Issues
594
595### Windows
596
597* Users must manually link `shlwapi.lib`. Failure to do so may result
Dominic Hamon62c68ba2016-09-23 12:44:22 -0700598in unresolved symbols.
599