• Home
Name Date Size #Lines LOC

..--

cmake/03-May-2024-426362

conan/03-May-2024-5837

docs/03-May-2024-349279

include/benchmark/03-May-2024-1,587826

src/03-May-2024-5,9874,190

test/03-May-2024-5,6484,431

tools/03-May-2024-1,7311,525

.clang-formatD03-May-202474 65

.gitignoreD03-May-2024713 6350

.travis-libcxx-setup.shD03-May-20241.1 KiB2919

.travis.ymlD03-May-20247.4 KiB236222

.ycm_extra_conf.pyD03-May-20243.6 KiB11676

AUTHORSD03-May-20242 KiB5755

Android.bpD03-May-20241.1 KiB4339

BUILD.bazelD03-May-2024986 4539

CMakeLists.txtD03-May-202411.1 KiB280250

CONTRIBUTING.mdD03-May-20242.4 KiB5941

CONTRIBUTORSD03-May-20243.1 KiB7977

LICENSED03-May-202411.1 KiB203169

METADATAD03-May-2024409 1918

MODULE_LICENSE_APACHE2D03-May-20240

NOTICED03-May-202411.1 KiB203169

OWNERSD03-May-202446 21

README.mdD03-May-202443.6 KiB1,2911,016

WORKSPACED03-May-2024571 1612

_config.ymlD03-May-202428 11

appveyor.ymlD03-May-20241.2 KiB5137

conanfile.pyD03-May-20243.1 KiB8062

dependencies.mdD03-May-2024647 1912

mingw.pyD03-May-202410.1 KiB321281

releasing.mdD03-May-2024647 1715

README.md

1# Benchmark
2
3[![Build Status](https://travis-ci.org/google/benchmark.svg?branch=master)](https://travis-ci.org/google/benchmark)
4[![Build status](https://ci.appveyor.com/api/projects/status/u0qsyp7t1tk7cpxs/branch/master?svg=true)](https://ci.appveyor.com/project/google/benchmark/branch/master)
5[![Coverage Status](https://coveralls.io/repos/google/benchmark/badge.svg)](https://coveralls.io/r/google/benchmark)
6[![slackin](https://slackin-iqtfqnpzxd.now.sh/badge.svg)](https://slackin-iqtfqnpzxd.now.sh/)
7
8A library to benchmark code snippets, similar to unit tests. Example:
9
10```c++
11#include <benchmark/benchmark.h>
12
13static void BM_SomeFunction(benchmark::State& state) {
14  // Perform setup here
15  for (auto _ : state) {
16    // This code gets timed
17    SomeFunction();
18  }
19}
20// Register the function as a benchmark
21BENCHMARK(BM_SomeFunction);
22// Run the benchmark
23BENCHMARK_MAIN();
24```
25
26To get started, see [Requirements](#requirements) and
27[Installation](#installation). See [Usage](#usage) for a full example and the
28[User Guide](#user-guide) for a more comprehensive feature overview.
29
30It may also help to read the [Google Test documentation](https://github.com/google/googletest/blob/master/googletest/docs/primer.md)
31as some of the structural aspects of the APIs are similar.
32
33### Resources
34
35[Discussion group](https://groups.google.com/d/forum/benchmark-discuss)
36
37IRC channel: [freenode](https://freenode.net) #googlebenchmark
38
39[Additional Tooling Documentation](docs/tools.md)
40
41[Assembly Testing Documentation](docs/AssemblyTests.md)
42
43## Requirements
44
45The library can be used with C++03. However, it requires C++11 to build,
46including compiler and standard library support.
47
48The following minimum versions are required to build the library:
49
50* GCC 4.8
51* Clang 3.4
52* Visual Studio 14 2015
53* Intel 2015 Update 1
54
55See [Platform-Specific Build Instructions](#platform-specific-build-instructions).
56
57## Installation
58
59This describes the installation process using cmake. As pre-requisites, you'll
60need git and cmake installed.
61
62_See [dependencies.md](dependencies.md) for more details regarding supported
63versions of build tools._
64
65```bash
66# Check out the library.
67$ git clone https://github.com/google/benchmark.git
68# Benchmark requires Google Test as a dependency. Add the source tree as a subdirectory.
69$ git clone https://github.com/google/googletest.git benchmark/googletest
70# Go to the library root directory
71$ cd benchmark
72# Make a build directory to place the build output.
73$ mkdir build && cd build
74# Generate a Makefile with cmake.
75# Use cmake -G <generator> to generate a different file type.
76$ cmake ../
77# Build the library.
78# Use make -j<number_of_parallel_jobs> to speed up the build process, e.g. make -j8 .
79$ make
80```
81This builds the `benchmark` and `benchmark_main` libraries and tests.
82On a unix system, the build directory should now look something like this:
83
84```
85/benchmark
86  /build
87    /src
88      /libbenchmark.a
89      /libbenchmark_main.a
90    /test
91      ...
92```
93
94Next, you can run the tests to check the build.
95
96```bash
97$ make test
98```
99
100If you want to install the library globally, also run:
101
102```
103sudo make install
104```
105
106Note that Google Benchmark requires Google Test to build and run the tests. This
107dependency can be provided two ways:
108
109* Checkout the Google Test sources into `benchmark/googletest` as above.
110* Otherwise, if `-DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON` is specified during
111  configuration, the library will automatically download and build any required
112  dependencies.
113
114If you do not wish to build and run the tests, add `-DBENCHMARK_ENABLE_GTEST_TESTS=OFF`
115to `CMAKE_ARGS`.
116
117### Debug vs Release
118
119By default, benchmark builds as a debug library. You will see a warning in the
120output when this is the case. To build it as a release library instead, use:
121
122```
123cmake -DCMAKE_BUILD_TYPE=Release
124```
125
126To enable link-time optimisation, use
127
128```
129cmake -DCMAKE_BUILD_TYPE=Release -DBENCHMARK_ENABLE_LTO=true
130```
131
132If you are using gcc, you might need to set `GCC_AR` and `GCC_RANLIB` cmake
133cache variables, if autodetection fails.
134
135If you are using clang, you may need to set `LLVMAR_EXECUTABLE`,
136`LLVMNM_EXECUTABLE` and `LLVMRANLIB_EXECUTABLE` cmake cache variables.
137
138
139### Stable and Experimental Library Versions
140
141The main branch contains the latest stable version of the benchmarking library;
142the API of which can be considered largely stable, with source breaking changes
143being made only upon the release of a new major version.
144
145Newer, experimental, features are implemented and tested on the
146[`v2` branch](https://github.com/google/benchmark/tree/v2). Users who wish
147to use, test, and provide feedback on the new features are encouraged to try
148this branch. However, this branch provides no stability guarantees and reserves
149the right to change and break the API at any time.
150
151## Usage
152
153### Basic usage
154
155Define a function that executes the code to measure, register it as a benchmark
156function using the `BENCHMARK` macro, and ensure an appropriate `main` function
157is available:
158
159```c++
160#include <benchmark/benchmark.h>
161
162static void BM_StringCreation(benchmark::State& state) {
163  for (auto _ : state)
164    std::string empty_string;
165}
166// Register the function as a benchmark
167BENCHMARK(BM_StringCreation);
168
169// Define another benchmark
170static void BM_StringCopy(benchmark::State& state) {
171  std::string x = "hello";
172  for (auto _ : state)
173    std::string copy(x);
174}
175BENCHMARK(BM_StringCopy);
176
177BENCHMARK_MAIN();
178```
179
180To run the benchmark, compile and link against the `benchmark` library
181(libbenchmark.a/.so). If you followed the build steps above, this library will
182be under the build directory you created.
183
184```bash
185# Example on linux after running the build steps above. Assumes the
186# `benchmark` and `build` directories are under the current directory.
187$ g++ mybenchmark.cc -std=c++11 -isystem benchmark/include \
188  -Lbenchmark/build/src -lbenchmark -lpthread -o mybenchmark
189```
190
191Alternatively, link against the `benchmark_main` library and remove
192`BENCHMARK_MAIN();` above to get the same behavior.
193
194The compiled executable will run all benchmarks by default. Pass the `--help`
195flag for option information or see the guide below.
196
197### Usage with CMake
198
199If using CMake, it is recommended to link against the project-provided
200`benchmark::benchmark` and `benchmark::benchmark_main` targets using
201`target_link_libraries`.
202It is possible to use ```find_package``` to import an installed version of the
203library.
204```cmake
205find_package(benchmark REQUIRED)
206```
207Alternatively, ```add_subdirectory``` will incorporate the library directly in
208to one's CMake project.
209```cmake
210add_subdirectory(benchmark)
211```
212Either way, link to the library as follows.
213```cmake
214target_link_libraries(MyTarget benchmark::benchmark)
215```
216
217## Platform Specific Build Instructions
218
219### Building with GCC
220
221When the library is built using GCC it is necessary to link with the pthread
222library due to how GCC implements `std::thread`. Failing to link to pthread will
223lead to runtime exceptions (unless you're using libc++), not linker errors. See
224[issue #67](https://github.com/google/benchmark/issues/67) for more details. You
225can link to pthread by adding `-pthread` to your linker command. Note, you can
226also use `-lpthread`, but there are potential issues with ordering of command
227line parameters if you use that.
228
229### Building with Visual Studio 2015 or 2017
230
231The `shlwapi` library (`-lshlwapi`) is required to support a call to `CPUInfo` which reads the registry. Either add `shlwapi.lib` under `[ Configuration Properties > Linker > Input ]`, or use the following:
232
233```
234// Alternatively, can add libraries using linker options.
235#ifdef _WIN32
236#pragma comment ( lib, "Shlwapi.lib" )
237#ifdef _DEBUG
238#pragma comment ( lib, "benchmarkd.lib" )
239#else
240#pragma comment ( lib, "benchmark.lib" )
241#endif
242#endif
243```
244
245Can also use the graphical version of CMake:
246* Open `CMake GUI`.
247* Under `Where to build the binaries`, same path as source plus `build`.
248* Under `CMAKE_INSTALL_PREFIX`, same path as source plus `install`.
249* Click `Configure`, `Generate`, `Open Project`.
250* If build fails, try deleting entire directory and starting again, or unticking options to build less.
251
252### Building with Intel 2015 Update 1 or Intel System Studio Update 4
253
254See instructions for building with Visual Studio. Once built, right click on the solution and change the build to Intel.
255
256### Building on Solaris
257
258If you're running benchmarks on solaris, you'll want the kstat library linked in
259too (`-lkstat`).
260
261## User Guide
262
263### Command Line
264
265[Output Formats](#output-formats)
266
267[Output Files](#output-files)
268
269[Running Benchmarks](#running-benchmarks)
270
271[Running a Subset of Benchmarks](#running-a-subset-of-benchmarks)
272
273[Result Comparison](#result-comparison)
274
275### Library
276
277[Runtime and Reporting Considerations](#runtime-and-reporting-considerations)
278
279[Passing Arguments](#passing-arguments)
280
281[Calculating Asymptotic Complexity](#asymptotic-complexity)
282
283[Templated Benchmarks](#templated-benchmarks)
284
285[Fixtures](#fixtures)
286
287[Custom Counters](#custom-counters)
288
289[Multithreaded Benchmarks](#multithreaded-benchmarks)
290
291[CPU Timers](#cpu-timers)
292
293[Manual Timing](#manual-timing)
294
295[Setting the Time Unit](#setting-the-time-unit)
296
297[Preventing Optimization](#preventing-optimization)
298
299[Reporting Statistics](#reporting-statistics)
300
301[Custom Statistics](#custom-statistics)
302
303[Using RegisterBenchmark](#using-register-benchmark)
304
305[Exiting with an Error](#exiting-with-an-error)
306
307[A Faster KeepRunning Loop](#a-faster-keep-running-loop)
308
309[Disabling CPU Frequency Scaling](#disabling-cpu-frequency-scaling)
310
311
312<a name="output-formats" />
313
314### Output Formats
315
316The library supports multiple output formats. Use the
317`--benchmark_format=<console|json|csv>` flag (or set the
318`BENCHMARK_FORMAT=<console|json|csv>` environment variable) to set
319the format type. `console` is the default format.
320
321The Console format is intended to be a human readable format. By default
322the format generates color output. Context is output on stderr and the
323tabular data on stdout. Example tabular output looks like:
324
325```
326Benchmark                               Time(ns)    CPU(ns) Iterations
327----------------------------------------------------------------------
328BM_SetInsert/1024/1                        28928      29349      23853  133.097kB/s   33.2742k items/s
329BM_SetInsert/1024/8                        32065      32913      21375  949.487kB/s   237.372k items/s
330BM_SetInsert/1024/10                       33157      33648      21431  1.13369MB/s   290.225k items/s
331```
332
333The JSON format outputs human readable json split into two top level attributes.
334The `context` attribute contains information about the run in general, including
335information about the CPU and the date.
336The `benchmarks` attribute contains a list of every benchmark run. Example json
337output looks like:
338
339```json
340{
341  "context": {
342    "date": "2015/03/17-18:40:25",
343    "num_cpus": 40,
344    "mhz_per_cpu": 2801,
345    "cpu_scaling_enabled": false,
346    "build_type": "debug"
347  },
348  "benchmarks": [
349    {
350      "name": "BM_SetInsert/1024/1",
351      "iterations": 94877,
352      "real_time": 29275,
353      "cpu_time": 29836,
354      "bytes_per_second": 134066,
355      "items_per_second": 33516
356    },
357    {
358      "name": "BM_SetInsert/1024/8",
359      "iterations": 21609,
360      "real_time": 32317,
361      "cpu_time": 32429,
362      "bytes_per_second": 986770,
363      "items_per_second": 246693
364    },
365    {
366      "name": "BM_SetInsert/1024/10",
367      "iterations": 21393,
368      "real_time": 32724,
369      "cpu_time": 33355,
370      "bytes_per_second": 1199226,
371      "items_per_second": 299807
372    }
373  ]
374}
375```
376
377The CSV format outputs comma-separated values. The `context` is output on stderr
378and the CSV itself on stdout. Example CSV output looks like:
379
380```
381name,iterations,real_time,cpu_time,bytes_per_second,items_per_second,label
382"BM_SetInsert/1024/1",65465,17890.7,8407.45,475768,118942,
383"BM_SetInsert/1024/8",116606,18810.1,9766.64,3.27646e+06,819115,
384"BM_SetInsert/1024/10",106365,17238.4,8421.53,4.74973e+06,1.18743e+06,
385```
386
387<a name="output-files" />
388
389### Output Files
390
391Write benchmark results to a file with the `--benchmark_out=<filename>` option
392(or set `BENCHMARK_OUT`). Specify the output format with
393`--benchmark_out_format={json|console|csv}` (or set
394`BENCHMARK_OUT_FORMAT={json|console|csv}`). Note that specifying
395`--benchmark_out` does not suppress the console output.
396
397<a name="running-benchmarks" />
398
399### Running Benchmarks
400
401Benchmarks are executed by running the produced binaries. Benchmarks binaries,
402by default, accept options that may be specified either through their command
403line interface or by setting environment variables before execution. For every
404`--option_flag=<value>` CLI switch, a corresponding environment variable
405`OPTION_FLAG=<value>` exist and is used as default if set (CLI switches always
406 prevails). A complete list of CLI options is available running benchmarks
407 with the `--help` switch.
408
409<a name="running-a-subset-of-benchmarks" />
410
411### Running a Subset of Benchmarks
412
413The `--benchmark_filter=<regex>` option (or `BENCHMARK_FILTER=<regex>`
414environment variable) can be used to only run the benchmarks that match
415the specified `<regex>`. For example:
416
417```bash
418$ ./run_benchmarks.x --benchmark_filter=BM_memcpy/32
419Run on (1 X 2300 MHz CPU )
4202016-06-25 19:34:24
421Benchmark              Time           CPU Iterations
422----------------------------------------------------
423BM_memcpy/32          11 ns         11 ns   79545455
424BM_memcpy/32k       2181 ns       2185 ns     324074
425BM_memcpy/32          12 ns         12 ns   54687500
426BM_memcpy/32k       1834 ns       1837 ns     357143
427```
428
429<a name="result-comparison" />
430
431### Result comparison
432
433It is possible to compare the benchmarking results.
434See [Additional Tooling Documentation](docs/tools.md)
435
436<a name="runtime-and-reporting-considerations" />
437
438### Runtime and Reporting Considerations
439
440When the benchmark binary is executed, each benchmark function is run serially.
441The number of iterations to run is determined dynamically by running the
442benchmark a few times and measuring the time taken and ensuring that the
443ultimate result will be statistically stable. As such, faster benchmark
444functions will be run for more iterations than slower benchmark functions, and
445the number of iterations is thus reported.
446
447In all cases, the number of iterations for which the benchmark is run is
448governed by the amount of time the benchmark takes. Concretely, the number of
449iterations is at least one, not more than 1e9, until CPU time is greater than
450the minimum time, or the wallclock time is 5x minimum time. The minimum time is
451set per benchmark by calling `MinTime` on the registered benchmark object.
452
453Average timings are then reported over the iterations run. If multiple
454repetitions are requested using the `--benchmark_repetitions` command-line
455option, or at registration time, the benchmark function will be run several
456times and statistical results across these repetitions will also be reported.
457
458As well as the per-benchmark entries, a preamble in the report will include
459information about the machine on which the benchmarks are run.
460
461<a name="passing-arguments" />
462
463### Passing Arguments
464
465Sometimes a family of benchmarks can be implemented with just one routine that
466takes an extra argument to specify which one of the family of benchmarks to
467run. For example, the following code defines a family of benchmarks for
468measuring the speed of `memcpy()` calls of different lengths:
469
470```c++
471static void BM_memcpy(benchmark::State& state) {
472  char* src = new char[state.range(0)];
473  char* dst = new char[state.range(0)];
474  memset(src, 'x', state.range(0));
475  for (auto _ : state)
476    memcpy(dst, src, state.range(0));
477  state.SetBytesProcessed(int64_t(state.iterations()) *
478                          int64_t(state.range(0)));
479  delete[] src;
480  delete[] dst;
481}
482BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10);
483```
484
485The preceding code is quite repetitive, and can be replaced with the following
486short-hand. The following invocation will pick a few appropriate arguments in
487the specified range and will generate a benchmark for each such argument.
488
489```c++
490BENCHMARK(BM_memcpy)->Range(8, 8<<10);
491```
492
493By default the arguments in the range are generated in multiples of eight and
494the command above selects [ 8, 64, 512, 4k, 8k ]. In the following code the
495range multiplier is changed to multiples of two.
496
497```c++
498BENCHMARK(BM_memcpy)->RangeMultiplier(2)->Range(8, 8<<10);
499```
500
501Now arguments generated are [ 8, 16, 32, 64, 128, 256, 512, 1024, 2k, 4k, 8k ].
502
503The preceding code shows a method of defining a sparse range.  The following
504example shows a method of defining a dense range. It is then used to benchmark
505the performance of `std::vector` initialization for uniformly increasing sizes.
506
507```c++
508static void BM_DenseRange(benchmark::State& state) {
509  for(auto _ : state) {
510    std::vector<int> v(state.range(0), state.range(0));
511    benchmark::DoNotOptimize(v.data());
512    benchmark::ClobberMemory();
513  }
514}
515BENCHMARK(BM_DenseRange)->DenseRange(0, 1024, 128);
516```
517
518Now arguments generated are [ 0, 128, 256, 384, 512, 640, 768, 896, 1024 ].
519
520You might have a benchmark that depends on two or more inputs. For example, the
521following code defines a family of benchmarks for measuring the speed of set
522insertion.
523
524```c++
525static void BM_SetInsert(benchmark::State& state) {
526  std::set<int> data;
527  for (auto _ : state) {
528    state.PauseTiming();
529    data = ConstructRandomSet(state.range(0));
530    state.ResumeTiming();
531    for (int j = 0; j < state.range(1); ++j)
532      data.insert(RandomNumber());
533  }
534}
535BENCHMARK(BM_SetInsert)
536    ->Args({1<<10, 128})
537    ->Args({2<<10, 128})
538    ->Args({4<<10, 128})
539    ->Args({8<<10, 128})
540    ->Args({1<<10, 512})
541    ->Args({2<<10, 512})
542    ->Args({4<<10, 512})
543    ->Args({8<<10, 512});
544```
545
546The preceding code is quite repetitive, and can be replaced with the following
547short-hand. The following macro will pick a few appropriate arguments in the
548product of the two specified ranges and will generate a benchmark for each such
549pair.
550
551```c++
552BENCHMARK(BM_SetInsert)->Ranges({{1<<10, 8<<10}, {128, 512}});
553```
554
555For more complex patterns of inputs, passing a custom function to `Apply` allows
556programmatic specification of an arbitrary set of arguments on which to run the
557benchmark. The following example enumerates a dense range on one parameter,
558and a sparse range on the second.
559
560```c++
561static void CustomArguments(benchmark::internal::Benchmark* b) {
562  for (int i = 0; i <= 10; ++i)
563    for (int j = 32; j <= 1024*1024; j *= 8)
564      b->Args({i, j});
565}
566BENCHMARK(BM_SetInsert)->Apply(CustomArguments);
567```
568
569#### Passing Arbitrary Arguments to a Benchmark
570
571In C++11 it is possible to define a benchmark that takes an arbitrary number
572of extra arguments. The `BENCHMARK_CAPTURE(func, test_case_name, ...args)`
573macro creates a benchmark that invokes `func`  with the `benchmark::State` as
574the first argument followed by the specified `args...`.
575The `test_case_name` is appended to the name of the benchmark and
576should describe the values passed.
577
578```c++
579template <class ...ExtraArgs>
580void BM_takes_args(benchmark::State& state, ExtraArgs&&... extra_args) {
581  [...]
582}
583// Registers a benchmark named "BM_takes_args/int_string_test" that passes
584// the specified values to `extra_args`.
585BENCHMARK_CAPTURE(BM_takes_args, int_string_test, 42, std::string("abc"));
586```
587
588Note that elements of `...args` may refer to global variables. Users should
589avoid modifying global state inside of a benchmark.
590
591<a name="asymptotic-complexity" />
592
593### Calculating Asymptotic Complexity (Big O)
594
595Asymptotic complexity might be calculated for a family of benchmarks. The
596following code will calculate the coefficient for the high-order term in the
597running time and the normalized root-mean square error of string comparison.
598
599```c++
600static void BM_StringCompare(benchmark::State& state) {
601  std::string s1(state.range(0), '-');
602  std::string s2(state.range(0), '-');
603  for (auto _ : state) {
604    benchmark::DoNotOptimize(s1.compare(s2));
605  }
606  state.SetComplexityN(state.range(0));
607}
608BENCHMARK(BM_StringCompare)
609    ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity(benchmark::oN);
610```
611
612As shown in the following invocation, asymptotic complexity might also be
613calculated automatically.
614
615```c++
616BENCHMARK(BM_StringCompare)
617    ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity();
618```
619
620The following code will specify asymptotic complexity with a lambda function,
621that might be used to customize high-order term calculation.
622
623```c++
624BENCHMARK(BM_StringCompare)->RangeMultiplier(2)
625    ->Range(1<<10, 1<<18)->Complexity([](int64_t n)->double{return n; });
626```
627
628<a name="templated-benchmarks" />
629
630### Templated Benchmarks
631
632This example produces and consumes messages of size `sizeof(v)` `range_x`
633times. It also outputs throughput in the absence of multiprogramming.
634
635```c++
636template <class Q> void BM_Sequential(benchmark::State& state) {
637  Q q;
638  typename Q::value_type v;
639  for (auto _ : state) {
640    for (int i = state.range(0); i--; )
641      q.push(v);
642    for (int e = state.range(0); e--; )
643      q.Wait(&v);
644  }
645  // actually messages, not bytes:
646  state.SetBytesProcessed(
647      static_cast<int64_t>(state.iterations())*state.range(0));
648}
649BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue<int>)->Range(1<<0, 1<<10);
650```
651
652Three macros are provided for adding benchmark templates.
653
654```c++
655#ifdef BENCHMARK_HAS_CXX11
656#define BENCHMARK_TEMPLATE(func, ...) // Takes any number of parameters.
657#else // C++ < C++11
658#define BENCHMARK_TEMPLATE(func, arg1)
659#endif
660#define BENCHMARK_TEMPLATE1(func, arg1)
661#define BENCHMARK_TEMPLATE2(func, arg1, arg2)
662```
663
664<a name="fixtures" />
665
666### Fixtures
667
668Fixture tests are created by first defining a type that derives from
669`::benchmark::Fixture` and then creating/registering the tests using the
670following macros:
671
672* `BENCHMARK_F(ClassName, Method)`
673* `BENCHMARK_DEFINE_F(ClassName, Method)`
674* `BENCHMARK_REGISTER_F(ClassName, Method)`
675
676For Example:
677
678```c++
679class MyFixture : public benchmark::Fixture {
680public:
681  void SetUp(const ::benchmark::State& state) {
682  }
683
684  void TearDown(const ::benchmark::State& state) {
685  }
686};
687
688BENCHMARK_F(MyFixture, FooTest)(benchmark::State& st) {
689   for (auto _ : st) {
690     ...
691  }
692}
693
694BENCHMARK_DEFINE_F(MyFixture, BarTest)(benchmark::State& st) {
695   for (auto _ : st) {
696     ...
697  }
698}
699/* BarTest is NOT registered */
700BENCHMARK_REGISTER_F(MyFixture, BarTest)->Threads(2);
701/* BarTest is now registered */
702```
703
704#### Templated Fixtures
705
706Also you can create templated fixture by using the following macros:
707
708* `BENCHMARK_TEMPLATE_F(ClassName, Method, ...)`
709* `BENCHMARK_TEMPLATE_DEFINE_F(ClassName, Method, ...)`
710
711For example:
712
713```c++
714template<typename T>
715class MyFixture : public benchmark::Fixture {};
716
717BENCHMARK_TEMPLATE_F(MyFixture, IntTest, int)(benchmark::State& st) {
718   for (auto _ : st) {
719     ...
720  }
721}
722
723BENCHMARK_TEMPLATE_DEFINE_F(MyFixture, DoubleTest, double)(benchmark::State& st) {
724   for (auto _ : st) {
725     ...
726  }
727}
728
729BENCHMARK_REGISTER_F(MyFixture, DoubleTest)->Threads(2);
730```
731
732<a name="custom-counters" />
733
734### Custom Counters
735
736You can add your own counters with user-defined names. The example below
737will add columns "Foo", "Bar" and "Baz" in its output:
738
739```c++
740static void UserCountersExample1(benchmark::State& state) {
741  double numFoos = 0, numBars = 0, numBazs = 0;
742  for (auto _ : state) {
743    // ... count Foo,Bar,Baz events
744  }
745  state.counters["Foo"] = numFoos;
746  state.counters["Bar"] = numBars;
747  state.counters["Baz"] = numBazs;
748}
749```
750
751The `state.counters` object is a `std::map` with `std::string` keys
752and `Counter` values. The latter is a `double`-like class, via an implicit
753conversion to `double&`. Thus you can use all of the standard arithmetic
754assignment operators (`=,+=,-=,*=,/=`) to change the value of each counter.
755
756In multithreaded benchmarks, each counter is set on the calling thread only.
757When the benchmark finishes, the counters from each thread will be summed;
758the resulting sum is the value which will be shown for the benchmark.
759
760The `Counter` constructor accepts three parameters: the value as a `double`
761; a bit flag which allows you to show counters as rates, and/or as per-thread
762iteration, and/or as per-thread averages, and/or iteration invariants,
763and/or finally inverting the result; and a flag specifying the 'unit' - i.e.
764is 1k a 1000 (default, `benchmark::Counter::OneK::kIs1000`), or 1024
765(`benchmark::Counter::OneK::kIs1024`)?
766
767```c++
768  // sets a simple counter
769  state.counters["Foo"] = numFoos;
770
771  // Set the counter as a rate. It will be presented divided
772  // by the duration of the benchmark.
773  // Meaning: per one second, how many 'foo's are processed?
774  state.counters["FooRate"] = Counter(numFoos, benchmark::Counter::kIsRate);
775
776  // Set the counter as a rate. It will be presented divided
777  // by the duration of the benchmark, and the result inverted.
778  // Meaning: how many seconds it takes to process one 'foo'?
779  state.counters["FooInvRate"] = Counter(numFoos, benchmark::Counter::kIsRate | benchmark::Counter::kInvert);
780
781  // Set the counter as a thread-average quantity. It will
782  // be presented divided by the number of threads.
783  state.counters["FooAvg"] = Counter(numFoos, benchmark::Counter::kAvgThreads);
784
785  // There's also a combined flag:
786  state.counters["FooAvgRate"] = Counter(numFoos,benchmark::Counter::kAvgThreadsRate);
787
788  // This says that we process with the rate of state.range(0) bytes every iteration:
789  state.counters["BytesProcessed"] = Counter(state.range(0), benchmark::Counter::kIsIterationInvariantRate, benchmark::Counter::OneK::kIs1024);
790```
791
792When you're compiling in C++11 mode or later you can use `insert()` with
793`std::initializer_list`:
794
795```c++
796  // With C++11, this can be done:
797  state.counters.insert({{"Foo", numFoos}, {"Bar", numBars}, {"Baz", numBazs}});
798  // ... instead of:
799  state.counters["Foo"] = numFoos;
800  state.counters["Bar"] = numBars;
801  state.counters["Baz"] = numBazs;
802```
803
804#### Counter Reporting
805
806When using the console reporter, by default, user counters are printed at
807the end after the table, the same way as ``bytes_processed`` and
808``items_processed``. This is best for cases in which there are few counters,
809or where there are only a couple of lines per benchmark. Here's an example of
810the default output:
811
812```
813------------------------------------------------------------------------------
814Benchmark                        Time           CPU Iterations UserCounters...
815------------------------------------------------------------------------------
816BM_UserCounter/threads:8      2248 ns      10277 ns      68808 Bar=16 Bat=40 Baz=24 Foo=8
817BM_UserCounter/threads:1      9797 ns       9788 ns      71523 Bar=2 Bat=5 Baz=3 Foo=1024m
818BM_UserCounter/threads:2      4924 ns       9842 ns      71036 Bar=4 Bat=10 Baz=6 Foo=2
819BM_UserCounter/threads:4      2589 ns      10284 ns      68012 Bar=8 Bat=20 Baz=12 Foo=4
820BM_UserCounter/threads:8      2212 ns      10287 ns      68040 Bar=16 Bat=40 Baz=24 Foo=8
821BM_UserCounter/threads:16     1782 ns      10278 ns      68144 Bar=32 Bat=80 Baz=48 Foo=16
822BM_UserCounter/threads:32     1291 ns      10296 ns      68256 Bar=64 Bat=160 Baz=96 Foo=32
823BM_UserCounter/threads:4      2615 ns      10307 ns      68040 Bar=8 Bat=20 Baz=12 Foo=4
824BM_Factorial                    26 ns         26 ns   26608979 40320
825BM_Factorial/real_time          26 ns         26 ns   26587936 40320
826BM_CalculatePiRange/1           16 ns         16 ns   45704255 0
827BM_CalculatePiRange/8           73 ns         73 ns    9520927 3.28374
828BM_CalculatePiRange/64         609 ns        609 ns    1140647 3.15746
829BM_CalculatePiRange/512       4900 ns       4901 ns     142696 3.14355
830```
831
832If this doesn't suit you, you can print each counter as a table column by
833passing the flag `--benchmark_counters_tabular=true` to the benchmark
834application. This is best for cases in which there are a lot of counters, or
835a lot of lines per individual benchmark. Note that this will trigger a
836reprinting of the table header any time the counter set changes between
837individual benchmarks. Here's an example of corresponding output when
838`--benchmark_counters_tabular=true` is passed:
839
840```
841---------------------------------------------------------------------------------------
842Benchmark                        Time           CPU Iterations    Bar   Bat   Baz   Foo
843---------------------------------------------------------------------------------------
844BM_UserCounter/threads:8      2198 ns       9953 ns      70688     16    40    24     8
845BM_UserCounter/threads:1      9504 ns       9504 ns      73787      2     5     3     1
846BM_UserCounter/threads:2      4775 ns       9550 ns      72606      4    10     6     2
847BM_UserCounter/threads:4      2508 ns       9951 ns      70332      8    20    12     4
848BM_UserCounter/threads:8      2055 ns       9933 ns      70344     16    40    24     8
849BM_UserCounter/threads:16     1610 ns       9946 ns      70720     32    80    48    16
850BM_UserCounter/threads:32     1192 ns       9948 ns      70496     64   160    96    32
851BM_UserCounter/threads:4      2506 ns       9949 ns      70332      8    20    12     4
852--------------------------------------------------------------
853Benchmark                        Time           CPU Iterations
854--------------------------------------------------------------
855BM_Factorial                    26 ns         26 ns   26392245 40320
856BM_Factorial/real_time          26 ns         26 ns   26494107 40320
857BM_CalculatePiRange/1           15 ns         15 ns   45571597 0
858BM_CalculatePiRange/8           74 ns         74 ns    9450212 3.28374
859BM_CalculatePiRange/64         595 ns        595 ns    1173901 3.15746
860BM_CalculatePiRange/512       4752 ns       4752 ns     147380 3.14355
861BM_CalculatePiRange/4k       37970 ns      37972 ns      18453 3.14184
862BM_CalculatePiRange/32k     303733 ns     303744 ns       2305 3.14162
863BM_CalculatePiRange/256k   2434095 ns    2434186 ns        288 3.1416
864BM_CalculatePiRange/1024k  9721140 ns    9721413 ns         71 3.14159
865BM_CalculatePi/threads:8      2255 ns       9943 ns      70936
866```
867
868Note above the additional header printed when the benchmark changes from
869``BM_UserCounter`` to ``BM_Factorial``. This is because ``BM_Factorial`` does
870not have the same counter set as ``BM_UserCounter``.
871
872<a name="multithreaded-benchmarks"/>
873
874### Multithreaded Benchmarks
875
876In a multithreaded test (benchmark invoked by multiple threads simultaneously),
877it is guaranteed that none of the threads will start until all have reached
878the start of the benchmark loop, and all will have finished before any thread
879exits the benchmark loop. (This behavior is also provided by the `KeepRunning()`
880API) As such, any global setup or teardown can be wrapped in a check against the thread
881index:
882
883```c++
884static void BM_MultiThreaded(benchmark::State& state) {
885  if (state.thread_index == 0) {
886    // Setup code here.
887  }
888  for (auto _ : state) {
889    // Run the test as normal.
890  }
891  if (state.thread_index == 0) {
892    // Teardown code here.
893  }
894}
895BENCHMARK(BM_MultiThreaded)->Threads(2);
896```
897
898If the benchmarked code itself uses threads and you want to compare it to
899single-threaded code, you may want to use real-time ("wallclock") measurements
900for latency comparisons:
901
902```c++
903BENCHMARK(BM_test)->Range(8, 8<<10)->UseRealTime();
904```
905
906Without `UseRealTime`, CPU time is used by default.
907
908<a name="cpu-timers" />
909
910### CPU Timers
911
912By default, the CPU timer only measures the time spent by the main thread.
913If the benchmark itself uses threads internally, this measurement may not
914be what you are looking for. Instead, there is a way to measure the total
915CPU usage of the process, by all the threads.
916
917```c++
918void callee(int i);
919
920static void MyMain(int size) {
921#pragma omp parallel for
922  for(int i = 0; i < size; i++)
923    callee(i);
924}
925
926static void BM_OpenMP(benchmark::State& state) {
927  for (auto _ : state)
928    MyMain(state.range(0));
929}
930
931// Measure the time spent by the main thread, use it to decide for how long to
932// run the benchmark loop. Depending on the internal implementation detail may
933// measure to anywhere from near-zero (the overhead spent before/after work
934// handoff to worker thread[s]) to the whole single-thread time.
935BENCHMARK(BM_OpenMP)->Range(8, 8<<10);
936
937// Measure the user-visible time, the wall clock (literally, the time that
938// has passed on the clock on the wall), use it to decide for how long to
939// run the benchmark loop. This will always be meaningful, an will match the
940// time spent by the main thread in single-threaded case, in general decreasing
941// with the number of internal threads doing the work.
942BENCHMARK(BM_OpenMP)->Range(8, 8<<10)->UseRealTime();
943
944// Measure the total CPU consumption, use it to decide for how long to
945// run the benchmark loop. This will always measure to no less than the
946// time spent by the main thread in single-threaded case.
947BENCHMARK(BM_OpenMP)->Range(8, 8<<10)->MeasureProcessCPUTime();
948
949// A mixture of the last two. Measure the total CPU consumption, but use the
950// wall clock to decide for how long to run the benchmark loop.
951BENCHMARK(BM_OpenMP)->Range(8, 8<<10)->MeasureProcessCPUTime()->UseRealTime();
952```
953
954#### Controlling Timers
955
956Normally, the entire duration of the work loop (`for (auto _ : state) {}`)
957is measured. But sometimes, it is necessary to do some work inside of
958that loop, every iteration, but without counting that time to the benchmark time.
959That is possible, although it is not recommended, since it has high overhead.
960
961```c++
962static void BM_SetInsert_With_Timer_Control(benchmark::State& state) {
963  std::set<int> data;
964  for (auto _ : state) {
965    state.PauseTiming(); // Stop timers. They will not count until they are resumed.
966    data = ConstructRandomSet(state.range(0)); // Do something that should not be measured
967    state.ResumeTiming(); // And resume timers. They are now counting again.
968    // The rest will be measured.
969    for (int j = 0; j < state.range(1); ++j)
970      data.insert(RandomNumber());
971  }
972}
973BENCHMARK(BM_SetInsert_With_Timer_Control)->Ranges({{1<<10, 8<<10}, {128, 512}});
974```
975
976<a name="manual-timing" />
977
978### Manual Timing
979
980For benchmarking something for which neither CPU time nor real-time are
981correct or accurate enough, completely manual timing is supported using
982the `UseManualTime` function.
983
984When `UseManualTime` is used, the benchmarked code must call
985`SetIterationTime` once per iteration of the benchmark loop to
986report the manually measured time.
987
988An example use case for this is benchmarking GPU execution (e.g. OpenCL
989or CUDA kernels, OpenGL or Vulkan or Direct3D draw calls), which cannot
990be accurately measured using CPU time or real-time. Instead, they can be
991measured accurately using a dedicated API, and these measurement results
992can be reported back with `SetIterationTime`.
993
994```c++
995static void BM_ManualTiming(benchmark::State& state) {
996  int microseconds = state.range(0);
997  std::chrono::duration<double, std::micro> sleep_duration {
998    static_cast<double>(microseconds)
999  };
1000
1001  for (auto _ : state) {
1002    auto start = std::chrono::high_resolution_clock::now();
1003    // Simulate some useful workload with a sleep
1004    std::this_thread::sleep_for(sleep_duration);
1005    auto end = std::chrono::high_resolution_clock::now();
1006
1007    auto elapsed_seconds =
1008      std::chrono::duration_cast<std::chrono::duration<double>>(
1009        end - start);
1010
1011    state.SetIterationTime(elapsed_seconds.count());
1012  }
1013}
1014BENCHMARK(BM_ManualTiming)->Range(1, 1<<17)->UseManualTime();
1015```
1016
1017<a name="setting-the-time-unit" />
1018
1019### Setting the Time Unit
1020
1021If a benchmark runs a few milliseconds it may be hard to visually compare the
1022measured times, since the output data is given in nanoseconds per default. In
1023order to manually set the time unit, you can specify it manually:
1024
1025```c++
1026BENCHMARK(BM_test)->Unit(benchmark::kMillisecond);
1027```
1028
1029<a name="preventing-optimization" />
1030
1031### Preventing Optimization
1032
1033To prevent a value or expression from being optimized away by the compiler
1034the `benchmark::DoNotOptimize(...)` and `benchmark::ClobberMemory()`
1035functions can be used.
1036
1037```c++
1038static void BM_test(benchmark::State& state) {
1039  for (auto _ : state) {
1040      int x = 0;
1041      for (int i=0; i < 64; ++i) {
1042        benchmark::DoNotOptimize(x += i);
1043      }
1044  }
1045}
1046```
1047
1048`DoNotOptimize(<expr>)` forces the  *result* of `<expr>` to be stored in either
1049memory or a register. For GNU based compilers it acts as read/write barrier
1050for global memory. More specifically it forces the compiler to flush pending
1051writes to memory and reload any other values as necessary.
1052
1053Note that `DoNotOptimize(<expr>)` does not prevent optimizations on `<expr>`
1054in any way. `<expr>` may even be removed entirely when the result is already
1055known. For example:
1056
1057```c++
1058  /* Example 1: `<expr>` is removed entirely. */
1059  int foo(int x) { return x + 42; }
1060  while (...) DoNotOptimize(foo(0)); // Optimized to DoNotOptimize(42);
1061
1062  /*  Example 2: Result of '<expr>' is only reused */
1063  int bar(int) __attribute__((const));
1064  while (...) DoNotOptimize(bar(0)); // Optimized to:
1065  // int __result__ = bar(0);
1066  // while (...) DoNotOptimize(__result__);
1067```
1068
1069The second tool for preventing optimizations is `ClobberMemory()`. In essence
1070`ClobberMemory()` forces the compiler to perform all pending writes to global
1071memory. Memory managed by block scope objects must be "escaped" using
1072`DoNotOptimize(...)` before it can be clobbered. In the below example
1073`ClobberMemory()` prevents the call to `v.push_back(42)` from being optimized
1074away.
1075
1076```c++
1077static void BM_vector_push_back(benchmark::State& state) {
1078  for (auto _ : state) {
1079    std::vector<int> v;
1080    v.reserve(1);
1081    benchmark::DoNotOptimize(v.data()); // Allow v.data() to be clobbered.
1082    v.push_back(42);
1083    benchmark::ClobberMemory(); // Force 42 to be written to memory.
1084  }
1085}
1086```
1087
1088Note that `ClobberMemory()` is only available for GNU or MSVC based compilers.
1089
1090<a name="reporting-statistics" />
1091
1092### Statistics: Reporting the Mean, Median and Standard Deviation of Repeated Benchmarks
1093
1094By default each benchmark is run once and that single result is reported.
1095However benchmarks are often noisy and a single result may not be representative
1096of the overall behavior. For this reason it's possible to repeatedly rerun the
1097benchmark.
1098
1099The number of runs of each benchmark is specified globally by the
1100`--benchmark_repetitions` flag or on a per benchmark basis by calling
1101`Repetitions` on the registered benchmark object. When a benchmark is run more
1102than once the mean, median and standard deviation of the runs will be reported.
1103
1104Additionally the `--benchmark_report_aggregates_only={true|false}`,
1105`--benchmark_display_aggregates_only={true|false}` flags or
1106`ReportAggregatesOnly(bool)`, `DisplayAggregatesOnly(bool)` functions can be
1107used to change how repeated tests are reported. By default the result of each
1108repeated run is reported. When `report aggregates only` option is `true`,
1109only the aggregates (i.e. mean, median and standard deviation, maybe complexity
1110measurements if they were requested) of the runs is reported, to both the
1111reporters - standard output (console), and the file.
1112However when only the `display aggregates only` option is `true`,
1113only the aggregates are displayed in the standard output, while the file
1114output still contains everything.
1115Calling `ReportAggregatesOnly(bool)` / `DisplayAggregatesOnly(bool)` on a
1116registered benchmark object overrides the value of the appropriate flag for that
1117benchmark.
1118
1119<a name="custom-statistics" />
1120
1121### Custom Statistics
1122
1123While having mean, median and standard deviation is nice, this may not be
1124enough for everyone. For example you may want to know what the largest
1125observation is, e.g. because you have some real-time constraints. This is easy.
1126The following code will specify a custom statistic to be calculated, defined
1127by a lambda function.
1128
1129```c++
1130void BM_spin_empty(benchmark::State& state) {
1131  for (auto _ : state) {
1132    for (int x = 0; x < state.range(0); ++x) {
1133      benchmark::DoNotOptimize(x);
1134    }
1135  }
1136}
1137
1138BENCHMARK(BM_spin_empty)
1139  ->ComputeStatistics("max", [](const std::vector<double>& v) -> double {
1140    return *(std::max_element(std::begin(v), std::end(v)));
1141  })
1142  ->Arg(512);
1143```
1144
1145<a name="using-register-benchmark" />
1146
1147### Using RegisterBenchmark(name, fn, args...)
1148
1149The `RegisterBenchmark(name, func, args...)` function provides an alternative
1150way to create and register benchmarks.
1151`RegisterBenchmark(name, func, args...)` creates, registers, and returns a
1152pointer to a new benchmark with the specified `name` that invokes
1153`func(st, args...)` where `st` is a `benchmark::State` object.
1154
1155Unlike the `BENCHMARK` registration macros, which can only be used at the global
1156scope, the `RegisterBenchmark` can be called anywhere. This allows for
1157benchmark tests to be registered programmatically.
1158
1159Additionally `RegisterBenchmark` allows any callable object to be registered
1160as a benchmark. Including capturing lambdas and function objects.
1161
1162For Example:
1163```c++
1164auto BM_test = [](benchmark::State& st, auto Inputs) { /* ... */ };
1165
1166int main(int argc, char** argv) {
1167  for (auto& test_input : { /* ... */ })
1168      benchmark::RegisterBenchmark(test_input.name(), BM_test, test_input);
1169  benchmark::Initialize(&argc, argv);
1170  benchmark::RunSpecifiedBenchmarks();
1171}
1172```
1173
1174<a name="exiting-with-an-error" />
1175
1176### Exiting with an Error
1177
1178When errors caused by external influences, such as file I/O and network
1179communication, occur within a benchmark the
1180`State::SkipWithError(const char* msg)` function can be used to skip that run
1181of benchmark and report the error. Note that only future iterations of the
1182`KeepRunning()` are skipped. For the ranged-for version of the benchmark loop
1183Users must explicitly exit the loop, otherwise all iterations will be performed.
1184Users may explicitly return to exit the benchmark immediately.
1185
1186The `SkipWithError(...)` function may be used at any point within the benchmark,
1187including before and after the benchmark loop.
1188
1189For example:
1190
1191```c++
1192static void BM_test(benchmark::State& state) {
1193  auto resource = GetResource();
1194  if (!resource.good()) {
1195      state.SkipWithError("Resource is not good!");
1196      // KeepRunning() loop will not be entered.
1197  }
1198  while (state.KeepRunning()) {
1199      auto data = resource.read_data();
1200      if (!resource.good()) {
1201        state.SkipWithError("Failed to read data!");
1202        break; // Needed to skip the rest of the iteration.
1203     }
1204     do_stuff(data);
1205  }
1206}
1207
1208static void BM_test_ranged_fo(benchmark::State & state) {
1209  state.SkipWithError("test will not be entered");
1210  for (auto _ : state) {
1211    state.SkipWithError("Failed!");
1212    break; // REQUIRED to prevent all further iterations.
1213  }
1214}
1215```
1216<a name="a-faster-keep-running-loop" />
1217
1218### A Faster KeepRunning Loop
1219
1220In C++11 mode, a ranged-based for loop should be used in preference to
1221the `KeepRunning` loop for running the benchmarks. For example:
1222
1223```c++
1224static void BM_Fast(benchmark::State &state) {
1225  for (auto _ : state) {
1226    FastOperation();
1227  }
1228}
1229BENCHMARK(BM_Fast);
1230```
1231
1232The reason the ranged-for loop is faster than using `KeepRunning`, is
1233because `KeepRunning` requires a memory load and store of the iteration count
1234ever iteration, whereas the ranged-for variant is able to keep the iteration count
1235in a register.
1236
1237For example, an empty inner loop of using the ranged-based for method looks like:
1238
1239```asm
1240# Loop Init
1241  mov rbx, qword ptr [r14 + 104]
1242  call benchmark::State::StartKeepRunning()
1243  test rbx, rbx
1244  je .LoopEnd
1245.LoopHeader: # =>This Inner Loop Header: Depth=1
1246  add rbx, -1
1247  jne .LoopHeader
1248.LoopEnd:
1249```
1250
1251Compared to an empty `KeepRunning` loop, which looks like:
1252
1253```asm
1254.LoopHeader: # in Loop: Header=BB0_3 Depth=1
1255  cmp byte ptr [rbx], 1
1256  jne .LoopInit
1257.LoopBody: # =>This Inner Loop Header: Depth=1
1258  mov rax, qword ptr [rbx + 8]
1259  lea rcx, [rax + 1]
1260  mov qword ptr [rbx + 8], rcx
1261  cmp rax, qword ptr [rbx + 104]
1262  jb .LoopHeader
1263  jmp .LoopEnd
1264.LoopInit:
1265  mov rdi, rbx
1266  call benchmark::State::StartKeepRunning()
1267  jmp .LoopBody
1268.LoopEnd:
1269```
1270
1271Unless C++03 compatibility is required, the ranged-for variant of writing
1272the benchmark loop should be preferred.
1273
1274<a name="disabling-cpu-frequency-scaling" />
1275
1276### Disabling CPU Frequency Scaling
1277
1278If you see this error:
1279
1280```
1281***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead.
1282```
1283
1284you might want to disable the CPU frequency scaling while running the benchmark:
1285
1286```bash
1287sudo cpupower frequency-set --governor performance
1288./mybench
1289sudo cpupower frequency-set --governor powersave
1290```
1291