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/)
7 A library to support the benchmarking of functions, similar to unit-tests.
9 Discussion group: https://groups.google.com/d/forum/benchmark-discuss
11 IRC channel: https://freenode.net #googlebenchmark
13 [Known issues and common problems](#known-issues)
15 [Additional Tooling Documentation](docs/tools.md)
17 [Assembly Testing Documentation](docs/AssemblyTests.md)
22 The basic steps for configuring and building the library look like this:
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
34 Note that Google Benchmark requires Google Test to build and run the tests. This
35 dependency can be provided two ways:
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
42 If you do not wish to build and run the tests, add `-DBENCHMARK_ENABLE_GTEST_TESTS=OFF`
48 For Ubuntu and Debian Based System
50 First make sure you have git and cmake installed (If not please install it)
53 sudo apt-get install git
54 sudo apt-get install cmake
57 Now, let's clone the repository and build it
60 git clone https://github.com/google/benchmark.git
62 git clone https://github.com/google/googletest.git
65 cmake .. -DCMAKE_BUILD_TYPE=RELEASE
69 We need to install the library globally now
75 Now you have google/benchmark installed in your machine
76 Note: Don't forget to link to pthread library while building
78 ## Stable and Experimental Library Versions
80 The main branch contains the latest stable version of the benchmarking library;
81 the API of which can be considered largely stable, with source breaking changes
82 being made only upon the release of a new major version.
84 Newer, experimental, features are implemented and tested on the
85 [`v2` branch](https://github.com/google/benchmark/tree/v2). Users who wish
86 to use, test, and provide feedback on the new features are encouraged to try
87 this branch. However, this branch provides no stability guarantees and reserves
88 the right to change and break the API at any time.
90 ##Prerequisite knowledge
92 Before 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:
93 https://github.com/google/googletest/blob/master/googletest/docs/Documentation.md
98 Define a function that executes the code to be measured.
101 #include <benchmark/benchmark.h>
103 static void BM_StringCreation(benchmark::State& state) {
105 std::string empty_string;
107 // Register the function as a benchmark
108 BENCHMARK(BM_StringCreation);
110 // Define another benchmark
111 static void BM_StringCopy(benchmark::State& state) {
112 std::string x = "hello";
116 BENCHMARK(BM_StringCopy);
121 Don'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.
126 The benchmark library will reporting the timing for the code within the `for(...)` loop.
128 ### Passing arguments
129 Sometimes a family of benchmarks can be implemented with just one routine that
130 takes an extra argument to specify which one of the family of benchmarks to
131 run. For example, the following code defines a family of benchmarks for
132 measuring the speed of `memcpy()` calls of different lengths:
135 static 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));
140 memcpy(dst, src, state.range(0));
141 state.SetBytesProcessed(int64_t(state.iterations()) *
142 int64_t(state.range(0)));
146 BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10);
149 The preceding code is quite repetitive, and can be replaced with the following
150 short-hand. The following invocation will pick a few appropriate arguments in
151 the specified range and will generate a benchmark for each such argument.
154 BENCHMARK(BM_memcpy)->Range(8, 8<<10);
157 By default the arguments in the range are generated in multiples of eight and
158 the command above selects [ 8, 64, 512, 4k, 8k ]. In the following code the
159 range multiplier is changed to multiples of two.
162 BENCHMARK(BM_memcpy)->RangeMultiplier(2)->Range(8, 8<<10);
164 Now arguments generated are [ 8, 16, 32, 64, 128, 256, 512, 1024, 2k, 4k, 8k ].
166 You might have a benchmark that depends on two or more inputs. For example, the
167 following code defines a family of benchmarks for measuring the speed of set
171 static void BM_SetInsert(benchmark::State& state) {
173 for (auto _ : state) {
175 data = ConstructRandomSet(state.range(0));
176 state.ResumeTiming();
177 for (int j = 0; j < state.range(1); ++j)
178 data.insert(RandomNumber());
181 BENCHMARK(BM_SetInsert)
189 ->Args({8<<10, 512});
192 The preceding code is quite repetitive, and can be replaced with the following
193 short-hand. The following macro will pick a few appropriate arguments in the
194 product of the two specified ranges and will generate a benchmark for each such
198 BENCHMARK(BM_SetInsert)->Ranges({{1<<10, 8<<10}, {128, 512}});
201 For more complex patterns of inputs, passing a custom function to `Apply` allows
202 programmatic specification of an arbitrary set of arguments on which to run the
203 benchmark. The following example enumerates a dense range on one parameter,
204 and a sparse range on the second.
207 static void CustomArguments(benchmark::internal::Benchmark* b) {
208 for (int i = 0; i <= 10; ++i)
209 for (int j = 32; j <= 1024*1024; j *= 8)
212 BENCHMARK(BM_SetInsert)->Apply(CustomArguments);
215 ### Calculate asymptotic complexity (Big O)
216 Asymptotic complexity might be calculated for a family of benchmarks. The
217 following code will calculate the coefficient for the high-order term in the
218 running time and the normalized root-mean square error of string comparison.
221 static 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));
227 state.SetComplexityN(state.range(0));
229 BENCHMARK(BM_StringCompare)
230 ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity(benchmark::oN);
233 As shown in the following invocation, asymptotic complexity might also be
234 calculated automatically.
237 BENCHMARK(BM_StringCompare)
238 ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity();
241 The following code will specify asymptotic complexity with a lambda function,
242 that might be used to customize high-order term calculation.
245 BENCHMARK(BM_StringCompare)->RangeMultiplier(2)
246 ->Range(1<<10, 1<<18)->Complexity([](int n)->double{return n; });
249 ### Templated benchmarks
250 Templated benchmarks work the same way: This example produces and consumes
251 messages of size `sizeof(v)` `range_x` times. It also outputs throughput in the
252 absence of multiprogramming.
255 template <class Q> int BM_Sequential(benchmark::State& state) {
257 typename Q::value_type v;
258 for (auto _ : state) {
259 for (int i = state.range(0); i--; )
261 for (int e = state.range(0); e--; )
264 // actually messages, not bytes:
265 state.SetBytesProcessed(
266 static_cast<int64_t>(state.iterations())*state.range(0));
268 BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue<int>)->Range(1<<0, 1<<10);
271 Three macros are provided for adding benchmark templates.
274 #ifdef BENCHMARK_HAS_CXX11
275 #define BENCHMARK_TEMPLATE(func, ...) // Takes any number of parameters.
277 #define BENCHMARK_TEMPLATE(func, arg1)
279 #define BENCHMARK_TEMPLATE1(func, arg1)
280 #define BENCHMARK_TEMPLATE2(func, arg1, arg2)
283 ### A Faster KeepRunning loop
285 In C++11 mode, a ranged-based for loop should be used in preference to
286 the `KeepRunning` loop for running the benchmarks. For example:
289 static void BM_Fast(benchmark::State &state) {
290 for (auto _ : state) {
297 The reason the ranged-for loop is faster than using `KeepRunning`, is
298 because `KeepRunning` requires a memory load and store of the iteration count
299 ever iteration, whereas the ranged-for variant is able to keep the iteration count
302 For example, an empty inner loop of using the ranged-based for method looks like:
306 mov rbx, qword ptr [r14 + 104]
307 call benchmark::State::StartKeepRunning()
310 .LoopHeader: # =>This Inner Loop Header: Depth=1
316 Compared to an empty `KeepRunning` loop, which looks like:
319 .LoopHeader: # in Loop: Header=BB0_3 Depth=1
320 cmp byte ptr [rbx], 1
322 .LoopBody: # =>This Inner Loop Header: Depth=1
323 mov rax, qword ptr [rbx + 8]
325 mov qword ptr [rbx + 8], rcx
326 cmp rax, qword ptr [rbx + 104]
331 call benchmark::State::StartKeepRunning()
336 Unless C++03 compatibility is required, the ranged-for variant of writing
337 the benchmark loop should be preferred.
339 ## Passing arbitrary arguments to a benchmark
340 In C++11 it is possible to define a benchmark that takes an arbitrary number
341 of extra arguments. The `BENCHMARK_CAPTURE(func, test_case_name, ...args)`
342 macro creates a benchmark that invokes `func` with the `benchmark::State` as
343 the first argument followed by the specified `args...`.
344 The `test_case_name` is appended to the name of the benchmark and
345 should describe the values passed.
348 template <class ...ExtraArgs>
349 void BM_takes_args(benchmark::State& state, ExtraArgs&&... extra_args) {
352 // Registers a benchmark named "BM_takes_args/int_string_test" that passes
353 // the specified values to `extra_args`.
354 BENCHMARK_CAPTURE(BM_takes_args, int_string_test, 42, std::string("abc"));
356 Note that elements of `...args` may refer to global variables. Users should
357 avoid modifying global state inside of a benchmark.
359 ## Using RegisterBenchmark(name, fn, args...)
361 The `RegisterBenchmark(name, func, args...)` function provides an alternative
362 way to create and register benchmarks.
363 `RegisterBenchmark(name, func, args...)` creates, registers, and returns a
364 pointer to a new benchmark with the specified `name` that invokes
365 `func(st, args...)` where `st` is a `benchmark::State` object.
367 Unlike the `BENCHMARK` registration macros, which can only be used at the global
368 scope, the `RegisterBenchmark` can be called anywhere. This allows for
369 benchmark tests to be registered programmatically.
371 Additionally `RegisterBenchmark` allows any callable object to be registered
372 as a benchmark. Including capturing lambdas and function objects.
376 auto BM_test = [](benchmark::State& st, auto Inputs) { /* ... */ };
378 int 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();
386 ### Multithreaded benchmarks
387 In a multithreaded test (benchmark invoked by multiple threads simultaneously),
388 it is guaranteed that none of the threads will start until all have reached
389 the start of the benchmark loop, and all will have finished before any thread
390 exits the benchmark loop. (This behavior is also provided by the `KeepRunning()`
391 API) As such, any global setup or teardown can be wrapped in a check against the thread
395 static void BM_MultiThreaded(benchmark::State& state) {
396 if (state.thread_index == 0) {
399 for (auto _ : state) {
400 // Run the test as normal.
402 if (state.thread_index == 0) {
403 // Teardown code here.
406 BENCHMARK(BM_MultiThreaded)->Threads(2);
409 If the benchmarked code itself uses threads and you want to compare it to
410 single-threaded code, you may want to use real-time ("wallclock") measurements
411 for latency comparisons:
414 BENCHMARK(BM_test)->Range(8, 8<<10)->UseRealTime();
417 Without `UseRealTime`, CPU time is used by default.
421 For benchmarking something for which neither CPU time nor real-time are
422 correct or accurate enough, completely manual timing is supported using
423 the `UseManualTime` function.
425 When `UseManualTime` is used, the benchmarked code must call
426 `SetIterationTime` once per iteration of the benchmark loop to
427 report the manually measured time.
429 An example use case for this is benchmarking GPU execution (e.g. OpenCL
430 or CUDA kernels, OpenGL or Vulkan or Direct3D draw calls), which cannot
431 be accurately measured using CPU time or real-time. Instead, they can be
432 measured accurately using a dedicated API, and these measurement results
433 can be reported back with `SetIterationTime`.
436 static 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)
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();
448 auto elapsed_seconds =
449 std::chrono::duration_cast<std::chrono::duration<double>>(
452 state.SetIterationTime(elapsed_seconds.count());
455 BENCHMARK(BM_ManualTiming)->Range(1, 1<<17)->UseManualTime();
458 ### Preventing optimisation
459 To prevent a value or expression from being optimized away by the compiler
460 the `benchmark::DoNotOptimize(...)` and `benchmark::ClobberMemory()`
461 functions can be used.
464 static void BM_test(benchmark::State& state) {
465 for (auto _ : state) {
467 for (int i=0; i < 64; ++i) {
468 benchmark::DoNotOptimize(x += i);
474 `DoNotOptimize(<expr>)` forces the *result* of `<expr>` to be stored in either
475 memory or a register. For GNU based compilers it acts as read/write barrier
476 for global memory. More specifically it forces the compiler to flush pending
477 writes to memory and reload any other values as necessary.
479 Note that `DoNotOptimize(<expr>)` does not prevent optimizations on `<expr>`
480 in any way. `<expr>` may even be removed entirely when the result is already
484 /* Example 1: `<expr>` is removed entirely. */
485 int foo(int x) { return x + 42; }
486 while (...) DoNotOptimize(foo(0)); // Optimized to DoNotOptimize(42);
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__);
495 The second tool for preventing optimizations is `ClobberMemory()`. In essence
496 `ClobberMemory()` forces the compiler to perform all pending writes to global
497 memory. 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
503 static void BM_vector_push_back(benchmark::State& state) {
504 for (auto _ : state) {
507 benchmark::DoNotOptimize(v.data()); // Allow v.data() to be clobbered.
509 benchmark::ClobberMemory(); // Force 42 to be written to memory.
514 Note that `ClobberMemory()` is only available for GNU or MSVC based compilers.
516 ### Set time unit manually
517 If a benchmark runs a few milliseconds it may be hard to visually compare the
518 measured times, since the output data is given in nanoseconds per default. In
519 order to manually set the time unit, you can specify it manually:
522 BENCHMARK(BM_test)->Unit(benchmark::kMillisecond);
525 ## Controlling number of iterations
526 In all cases, the number of iterations for which the benchmark is run is
527 governed by the amount of time the benchmark takes. Concretely, the number of
528 iterations is at least one, not more than 1e9, until CPU time is greater than
529 the minimum time, or the wallclock time is 5x minimum time. The minimum time is
530 set as a flag `--benchmark_min_time` or per benchmark by calling `MinTime` on
531 the registered benchmark object.
533 ## Reporting the mean, median and standard deviation by repeated benchmarks
534 By default each benchmark is run once and that single result is reported.
535 However benchmarks are often noisy and a single result may not be representative
536 of the overall behavior. For this reason it's possible to repeatedly rerun the
539 The 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
542 than once the mean, median and standard deviation of the runs will be reported.
544 Additionally the `--benchmark_report_aggregates_only={true|false}` flag or
545 `ReportAggregatesOnly(bool)` function can be used to change how repeated tests
546 are reported. By default the result of each repeated run is reported. When this
547 option is `true` only the mean, median and standard deviation of the runs is reported.
548 Calling `ReportAggregatesOnly(bool)` on a registered benchmark object overrides
549 the value of the flag for that benchmark.
551 ## User-defined statistics for repeated benchmarks
552 While having mean, median and standard deviation is nice, this may not be
553 enough for everyone. For example you may want to know what is the largest
554 observation, e.g. because you have some real-time constraints. This is easy.
555 The following code will specify a custom statistic to be calculated, defined
556 by a lambda function.
559 void BM_spin_empty(benchmark::State& state) {
560 for (auto _ : state) {
561 for (int x = 0; x < state.range(0); ++x) {
562 benchmark::DoNotOptimize(x);
567 BENCHMARK(BM_spin_empty)
568 ->ComputeStatistics("max", [](const std::vector<double>& v) -> double {
569 return *(std::max_element(std::begin(v), std::end(v)));
575 Fixture tests are created by
576 first defining a type that derives from `::benchmark::Fixture` and then
577 creating/registering the tests using the following macros:
579 * `BENCHMARK_F(ClassName, Method)`
580 * `BENCHMARK_DEFINE_F(ClassName, Method)`
581 * `BENCHMARK_REGISTER_F(ClassName, Method)`
586 class MyFixture : public benchmark::Fixture {};
588 BENCHMARK_F(MyFixture, FooTest)(benchmark::State& st) {
594 BENCHMARK_DEFINE_F(MyFixture, BarTest)(benchmark::State& st) {
599 /* BarTest is NOT registered */
600 BENCHMARK_REGISTER_F(MyFixture, BarTest)->Threads(2);
601 /* BarTest is now registered */
604 ### Templated fixtures
605 Also you can create templated fixture by using the following macros:
607 * `BENCHMARK_TEMPLATE_F(ClassName, Method, ...)`
608 * `BENCHMARK_TEMPLATE_DEFINE_F(ClassName, Method, ...)`
613 class MyFixture : public benchmark::Fixture {};
615 BENCHMARK_TEMPLATE_F(MyFixture, IntTest, int)(benchmark::State& st) {
621 BENCHMARK_TEMPLATE_DEFINE_F(MyFixture, DoubleTest, double)(benchmark::State& st) {
627 BENCHMARK_REGISTER_F(MyFixture, DoubleTest)->Threads(2);
630 ## User-defined counters
632 You can add your own counters with user-defined names. The example below
633 will add columns "Foo", "Bar" and "Baz" in its output:
636 static void UserCountersExample1(benchmark::State& state) {
637 double numFoos = 0, numBars = 0, numBazs = 0;
638 for (auto _ : state) {
639 // ... count Foo,Bar,Baz events
641 state.counters["Foo"] = numFoos;
642 state.counters["Bar"] = numBars;
643 state.counters["Baz"] = numBazs;
647 The `state.counters` object is a `std::map` with `std::string` keys
648 and `Counter` values. The latter is a `double`-like class, via an implicit
649 conversion to `double&`. Thus you can use all of the standard arithmetic
650 assignment operators (`=,+=,-=,*=,/=`) to change the value of each counter.
652 In multithreaded benchmarks, each counter is set on the calling thread only.
653 When the benchmark finishes, the counters from each thread will be summed;
654 the resulting sum is the value which will be shown for the benchmark.
656 The `Counter` constructor accepts two parameters: the value as a `double`
657 and a bit flag which allows you to show counters as rates and/or as
661 // sets a simple counter
662 state.counters["Foo"] = numFoos;
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);
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);
672 // There's also a combined flag:
673 state.counters["FooAvgRate"] = Counter(numFoos,benchmark::Counter::kAvgThreadsRate);
676 When you're compiling in C++11 mode or later you can use `insert()` with
677 `std::initializer_list`:
680 // With C++11, this can be done:
681 state.counters.insert({{"Foo", numFoos}, {"Bar", numBars}, {"Baz", numBazs}});
683 state.counters["Foo"] = numFoos;
684 state.counters["Bar"] = numBars;
685 state.counters["Baz"] = numBazs;
688 ### Counter reporting
690 When using the console reporter, by default, user counters are are printed at
691 the 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,
693 or where there are only a couple of lines per benchmark. Here's an example of
697 ------------------------------------------------------------------------------
698 Benchmark Time CPU Iterations UserCounters...
699 ------------------------------------------------------------------------------
700 BM_UserCounter/threads:8 2248 ns 10277 ns 68808 Bar=16 Bat=40 Baz=24 Foo=8
701 BM_UserCounter/threads:1 9797 ns 9788 ns 71523 Bar=2 Bat=5 Baz=3 Foo=1024m
702 BM_UserCounter/threads:2 4924 ns 9842 ns 71036 Bar=4 Bat=10 Baz=6 Foo=2
703 BM_UserCounter/threads:4 2589 ns 10284 ns 68012 Bar=8 Bat=20 Baz=12 Foo=4
704 BM_UserCounter/threads:8 2212 ns 10287 ns 68040 Bar=16 Bat=40 Baz=24 Foo=8
705 BM_UserCounter/threads:16 1782 ns 10278 ns 68144 Bar=32 Bat=80 Baz=48 Foo=16
706 BM_UserCounter/threads:32 1291 ns 10296 ns 68256 Bar=64 Bat=160 Baz=96 Foo=32
707 BM_UserCounter/threads:4 2615 ns 10307 ns 68040 Bar=8 Bat=20 Baz=12 Foo=4
708 BM_Factorial 26 ns 26 ns 26608979 40320
709 BM_Factorial/real_time 26 ns 26 ns 26587936 40320
710 BM_CalculatePiRange/1 16 ns 16 ns 45704255 0
711 BM_CalculatePiRange/8 73 ns 73 ns 9520927 3.28374
712 BM_CalculatePiRange/64 609 ns 609 ns 1140647 3.15746
713 BM_CalculatePiRange/512 4900 ns 4901 ns 142696 3.14355
716 If this doesn't suit you, you can print each counter as a table column by
717 passing the flag `--benchmark_counters_tabular=true` to the benchmark
718 application. This is best for cases in which there are a lot of counters, or
719 a lot of lines per individual benchmark. Note that this will trigger a
720 reprinting of the table header any time the counter set changes between
721 individual benchmarks. Here's an example of corresponding output when
722 `--benchmark_counters_tabular=true` is passed:
725 ---------------------------------------------------------------------------------------
726 Benchmark Time CPU Iterations Bar Bat Baz Foo
727 ---------------------------------------------------------------------------------------
728 BM_UserCounter/threads:8 2198 ns 9953 ns 70688 16 40 24 8
729 BM_UserCounter/threads:1 9504 ns 9504 ns 73787 2 5 3 1
730 BM_UserCounter/threads:2 4775 ns 9550 ns 72606 4 10 6 2
731 BM_UserCounter/threads:4 2508 ns 9951 ns 70332 8 20 12 4
732 BM_UserCounter/threads:8 2055 ns 9933 ns 70344 16 40 24 8
733 BM_UserCounter/threads:16 1610 ns 9946 ns 70720 32 80 48 16
734 BM_UserCounter/threads:32 1192 ns 9948 ns 70496 64 160 96 32
735 BM_UserCounter/threads:4 2506 ns 9949 ns 70332 8 20 12 4
736 --------------------------------------------------------------
737 Benchmark Time CPU Iterations
738 --------------------------------------------------------------
739 BM_Factorial 26 ns 26 ns 26392245 40320
740 BM_Factorial/real_time 26 ns 26 ns 26494107 40320
741 BM_CalculatePiRange/1 15 ns 15 ns 45571597 0
742 BM_CalculatePiRange/8 74 ns 74 ns 9450212 3.28374
743 BM_CalculatePiRange/64 595 ns 595 ns 1173901 3.15746
744 BM_CalculatePiRange/512 4752 ns 4752 ns 147380 3.14355
745 BM_CalculatePiRange/4k 37970 ns 37972 ns 18453 3.14184
746 BM_CalculatePiRange/32k 303733 ns 303744 ns 2305 3.14162
747 BM_CalculatePiRange/256k 2434095 ns 2434186 ns 288 3.1416
748 BM_CalculatePiRange/1024k 9721140 ns 9721413 ns 71 3.14159
749 BM_CalculatePi/threads:8 2255 ns 9943 ns 70936
751 Note above the additional header printed when the benchmark changes from
752 ``BM_UserCounter`` to ``BM_Factorial``. This is because ``BM_Factorial`` does
753 not have the same counter set as ``BM_UserCounter``.
755 ## Exiting Benchmarks in Error
757 When errors caused by external influences, such as file I/O and network
758 communication, occur within a benchmark the
759 `State::SkipWithError(const char* msg)` function can be used to skip that run
760 of 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
762 Users must explicitly exit the loop, otherwise all iterations will be performed.
763 Users may explicitly return to exit the benchmark immediately.
765 The `SkipWithError(...)` function may be used at any point within the benchmark,
766 including before and after the benchmark loop.
771 static 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.
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.
787 static 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.
796 ## Running a subset of the benchmarks
798 The `--benchmark_filter=<regex>` option can be used to only run the benchmarks
799 which match the specified `<regex>`. For example:
802 $ ./run_benchmarks.x --benchmark_filter=BM_memcpy/32
803 Run on (1 X 2300 MHz CPU )
805 Benchmark Time CPU Iterations
806 ----------------------------------------------------
807 BM_memcpy/32 11 ns 11 ns 79545455
808 BM_memcpy/32k 2181 ns 2185 ns 324074
809 BM_memcpy/32 12 ns 12 ns 54687500
810 BM_memcpy/32k 1834 ns 1837 ns 357143
815 The library supports multiple output formats. Use the
816 `--benchmark_format=<console|json|csv>` flag to set the format type. `console`
817 is the default format.
819 The Console format is intended to be a human readable format. By default
820 the format generates color output. Context is output on stderr and the
821 tabular data on stdout. Example tabular output looks like:
823 Benchmark Time(ns) CPU(ns) Iterations
824 ----------------------------------------------------------------------
825 BM_SetInsert/1024/1 28928 29349 23853 133.097kB/s 33.2742k items/s
826 BM_SetInsert/1024/8 32065 32913 21375 949.487kB/s 237.372k items/s
827 BM_SetInsert/1024/10 33157 33648 21431 1.13369MB/s 290.225k items/s
830 The JSON format outputs human readable json split into two top level attributes.
831 The `context` attribute contains information about the run in general, including
832 information about the CPU and the date.
833 The `benchmarks` attribute contains a list of every benchmark run. Example json
838 "date": "2015/03/17-18:40:25",
841 "cpu_scaling_enabled": false,
842 "build_type": "debug"
846 "name": "BM_SetInsert/1024/1",
850 "bytes_per_second": 134066,
851 "items_per_second": 33516
854 "name": "BM_SetInsert/1024/8",
858 "bytes_per_second": 986770,
859 "items_per_second": 246693
862 "name": "BM_SetInsert/1024/10",
866 "bytes_per_second": 1199226,
867 "items_per_second": 299807
873 The CSV format outputs comma-separated values. The `context` is output on stderr
874 and the CSV itself on stdout. Example CSV output looks like:
876 name,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,
883 The library supports writing the output of the benchmark to a file specified
884 by `--benchmark_out=<filename>`. The format of the output can be specified
885 using `--benchmark_out_format={json|console|csv}`. Specifying
886 `--benchmark_out` does not suppress the console output.
889 By 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:
892 cmake -DCMAKE_BUILD_TYPE=Release
895 To enable link-time optimisation, use
898 cmake -DCMAKE_BUILD_TYPE=Release -DBENCHMARK_ENABLE_LTO=true
901 If you are using gcc, you might need to set `GCC_AR` and `GCC_RANLIB` cmake cache variables, if autodetection fails.
902 If you are using clang, you may need to set `LLVMAR_EXECUTABLE`, `LLVMNM_EXECUTABLE` and `LLVMRANLIB_EXECUTABLE` cmake cache variables.
904 ## Linking against the library
906 When the library is built using GCC it is necessary to link with `-pthread`,
907 due to how GCC implements `std::thread`.
909 For GCC 4.x failing to link to pthreads will lead to runtime exceptions, not linker errors.
910 See [issue #67](https://github.com/google/benchmark/issues/67) for more details.
914 Google Benchmark uses C++11 when building the library. As such we require
915 a modern C++ toolchain, both compiler and standard library.
917 The following minimum versions are strongly recommended build the library:
922 * Intel 2015 Update 1
924 Anything older *may* work.
926 Note: Using the library and its headers in C++03 is supported. C++11 is only
927 required to build the library.
929 ## Disable CPU frequency scaling
930 If you see this error:
932 ***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead.
934 you might want to disable the CPU frequency scaling while running the benchmark:
936 sudo cpupower frequency-set --governor performance
938 sudo cpupower frequency-set --governor powersave
943 ### Windows with CMake
945 * Users must manually link `shlwapi.lib`. Failure to do so may result
946 in unresolved symbols.
950 * Users must explicitly link with kstat library (-lkstat compilation flag).