benchmark.h 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551
  1. // Copyright 2015 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Support for registering benchmarks for functions.
  15. /* Example usage:
  16. // Define a function that executes the code to be measured a
  17. // specified number of times:
  18. static void BM_StringCreation(benchmark::State& state) {
  19. for (auto _ : state)
  20. std::string empty_string;
  21. }
  22. // Register the function as a benchmark
  23. BENCHMARK(BM_StringCreation);
  24. // Define another benchmark
  25. static void BM_StringCopy(benchmark::State& state) {
  26. std::string x = "hello";
  27. for (auto _ : state)
  28. std::string copy(x);
  29. }
  30. BENCHMARK(BM_StringCopy);
  31. // Augment the main() program to invoke benchmarks if specified
  32. // via the --benchmarks command line flag. E.g.,
  33. // my_unittest --benchmark_filter=all
  34. // my_unittest --benchmark_filter=BM_StringCreation
  35. // my_unittest --benchmark_filter=String
  36. // my_unittest --benchmark_filter='Copy|Creation'
  37. int main(int argc, char** argv) {
  38. benchmark::Initialize(&argc, argv);
  39. benchmark::RunSpecifiedBenchmarks();
  40. return 0;
  41. }
  42. // Sometimes a family of microbenchmarks can be implemented with
  43. // just one routine that takes an extra argument to specify which
  44. // one of the family of benchmarks to run. For example, the following
  45. // code defines a family of microbenchmarks for measuring the speed
  46. // of memcpy() calls of different lengths:
  47. static void BM_memcpy(benchmark::State& state) {
  48. char* src = new char[state.range(0)]; char* dst = new char[state.range(0)];
  49. memset(src, 'x', state.range(0));
  50. for (auto _ : state)
  51. memcpy(dst, src, state.range(0));
  52. state.SetBytesProcessed(int64_t(state.iterations()) *
  53. int64_t(state.range(0)));
  54. delete[] src; delete[] dst;
  55. }
  56. BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10);
  57. // The preceding code is quite repetitive, and can be replaced with the
  58. // following short-hand. The following invocation will pick a few
  59. // appropriate arguments in the specified range and will generate a
  60. // microbenchmark for each such argument.
  61. BENCHMARK(BM_memcpy)->Range(8, 8<<10);
  62. // You might have a microbenchmark that depends on two inputs. For
  63. // example, the following code defines a family of microbenchmarks for
  64. // measuring the speed of set insertion.
  65. static void BM_SetInsert(benchmark::State& state) {
  66. set<int> data;
  67. for (auto _ : state) {
  68. state.PauseTiming();
  69. data = ConstructRandomSet(state.range(0));
  70. state.ResumeTiming();
  71. for (int j = 0; j < state.range(1); ++j)
  72. data.insert(RandomNumber());
  73. }
  74. }
  75. BENCHMARK(BM_SetInsert)
  76. ->Args({1<<10, 128})
  77. ->Args({2<<10, 128})
  78. ->Args({4<<10, 128})
  79. ->Args({8<<10, 128})
  80. ->Args({1<<10, 512})
  81. ->Args({2<<10, 512})
  82. ->Args({4<<10, 512})
  83. ->Args({8<<10, 512});
  84. // The preceding code is quite repetitive, and can be replaced with
  85. // the following short-hand. The following macro will pick a few
  86. // appropriate arguments in the product of the two specified ranges
  87. // and will generate a microbenchmark for each such pair.
  88. BENCHMARK(BM_SetInsert)->Ranges({{1<<10, 8<<10}, {128, 512}});
  89. // For more complex patterns of inputs, passing a custom function
  90. // to Apply allows programmatic specification of an
  91. // arbitrary set of arguments to run the microbenchmark on.
  92. // The following example enumerates a dense range on
  93. // one parameter, and a sparse range on the second.
  94. static void CustomArguments(benchmark::internal::Benchmark* b) {
  95. for (int i = 0; i <= 10; ++i)
  96. for (int j = 32; j <= 1024*1024; j *= 8)
  97. b->Args({i, j});
  98. }
  99. BENCHMARK(BM_SetInsert)->Apply(CustomArguments);
  100. // Templated microbenchmarks work the same way:
  101. // Produce then consume 'size' messages 'iters' times
  102. // Measures throughput in the absence of multiprogramming.
  103. template <class Q> int BM_Sequential(benchmark::State& state) {
  104. Q q;
  105. typename Q::value_type v;
  106. for (auto _ : state) {
  107. for (int i = state.range(0); i--; )
  108. q.push(v);
  109. for (int e = state.range(0); e--; )
  110. q.Wait(&v);
  111. }
  112. // actually messages, not bytes:
  113. state.SetBytesProcessed(
  114. static_cast<int64_t>(state.iterations())*state.range(0));
  115. }
  116. BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue<int>)->Range(1<<0, 1<<10);
  117. Use `Benchmark::MinTime(double t)` to set the minimum time used to run the
  118. benchmark. This option overrides the `benchmark_min_time` flag.
  119. void BM_test(benchmark::State& state) {
  120. ... body ...
  121. }
  122. BENCHMARK(BM_test)->MinTime(2.0); // Run for at least 2 seconds.
  123. In a multithreaded test, it is guaranteed that none of the threads will start
  124. until all have reached the loop start, and all will have finished before any
  125. thread exits the loop body. As such, any global setup or teardown you want to
  126. do can be wrapped in a check against the thread index:
  127. static void BM_MultiThreaded(benchmark::State& state) {
  128. if (state.thread_index == 0) {
  129. // Setup code here.
  130. }
  131. for (auto _ : state) {
  132. // Run the test as normal.
  133. }
  134. if (state.thread_index == 0) {
  135. // Teardown code here.
  136. }
  137. }
  138. BENCHMARK(BM_MultiThreaded)->Threads(4);
  139. If a benchmark runs a few milliseconds it may be hard to visually compare the
  140. measured times, since the output data is given in nanoseconds per default. In
  141. order to manually set the time unit, you can specify it manually:
  142. BENCHMARK(BM_test)->Unit(benchmark::kMillisecond);
  143. */
  144. #ifndef BENCHMARK_BENCHMARK_H_
  145. #define BENCHMARK_BENCHMARK_H_
  146. // The _MSVC_LANG check should detect Visual Studio 2015 Update 3 and newer.
  147. #if __cplusplus >= 201103L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201103L)
  148. #define BENCHMARK_HAS_CXX11
  149. #endif
  150. #include <stdint.h>
  151. #include <algorithm>
  152. #include <cassert>
  153. #include <cstddef>
  154. #include <iosfwd>
  155. #include <map>
  156. #include <set>
  157. #include <string>
  158. #include <vector>
  159. #if defined(BENCHMARK_HAS_CXX11)
  160. #include <initializer_list>
  161. #include <type_traits>
  162. #include <utility>
  163. #endif
  164. #if defined(_MSC_VER)
  165. #include <intrin.h> // for _ReadWriteBarrier
  166. #endif
  167. #ifndef BENCHMARK_HAS_CXX11
  168. #define BENCHMARK_DISALLOW_COPY_AND_ASSIGN(TypeName) \
  169. TypeName(const TypeName&); \
  170. TypeName& operator=(const TypeName&)
  171. #else
  172. #define BENCHMARK_DISALLOW_COPY_AND_ASSIGN(TypeName) \
  173. TypeName(const TypeName&) = delete; \
  174. TypeName& operator=(const TypeName&) = delete
  175. #endif
  176. #if defined(__GNUC__)
  177. #define BENCHMARK_UNUSED __attribute__((unused))
  178. #define BENCHMARK_ALWAYS_INLINE __attribute__((always_inline))
  179. #define BENCHMARK_NOEXCEPT noexcept
  180. #define BENCHMARK_NOEXCEPT_OP(x) noexcept(x)
  181. #elif defined(_MSC_VER) && !defined(__clang__)
  182. #define BENCHMARK_UNUSED
  183. #define BENCHMARK_ALWAYS_INLINE __forceinline
  184. #if _MSC_VER >= 1900
  185. #define BENCHMARK_NOEXCEPT noexcept
  186. #define BENCHMARK_NOEXCEPT_OP(x) noexcept(x)
  187. #else
  188. #define BENCHMARK_NOEXCEPT
  189. #define BENCHMARK_NOEXCEPT_OP(x)
  190. #endif
  191. #define __func__ __FUNCTION__
  192. #else
  193. #define BENCHMARK_UNUSED
  194. #define BENCHMARK_ALWAYS_INLINE
  195. #define BENCHMARK_NOEXCEPT
  196. #define BENCHMARK_NOEXCEPT_OP(x)
  197. #endif
  198. #define BENCHMARK_INTERNAL_TOSTRING2(x) #x
  199. #define BENCHMARK_INTERNAL_TOSTRING(x) BENCHMARK_INTERNAL_TOSTRING2(x)
  200. #if defined(__GNUC__) || defined(__clang__)
  201. #define BENCHMARK_BUILTIN_EXPECT(x, y) __builtin_expect(x, y)
  202. #define BENCHMARK_DEPRECATED_MSG(msg) __attribute__((deprecated(msg)))
  203. #else
  204. #define BENCHMARK_BUILTIN_EXPECT(x, y) x
  205. #define BENCHMARK_DEPRECATED_MSG(msg)
  206. #define BENCHMARK_WARNING_MSG(msg) \
  207. __pragma(message(__FILE__ "(" BENCHMARK_INTERNAL_TOSTRING( \
  208. __LINE__) ") : warning note: " msg))
  209. #endif
  210. #if defined(__GNUC__) && !defined(__clang__)
  211. #define BENCHMARK_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
  212. #endif
  213. #ifndef __has_builtin
  214. #define __has_builtin(x) 0
  215. #endif
  216. #if defined(__GNUC__) || __has_builtin(__builtin_unreachable)
  217. #define BENCHMARK_UNREACHABLE() __builtin_unreachable()
  218. #elif defined(_MSC_VER)
  219. #define BENCHMARK_UNREACHABLE() __assume(false)
  220. #else
  221. #define BENCHMARK_UNREACHABLE() ((void)0)
  222. #endif
  223. namespace benchmark {
  224. class BenchmarkReporter;
  225. class MemoryManager;
  226. void Initialize(int* argc, char** argv);
  227. // Report to stdout all arguments in 'argv' as unrecognized except the first.
  228. // Returns true there is at least on unrecognized argument (i.e. 'argc' > 1).
  229. bool ReportUnrecognizedArguments(int argc, char** argv);
  230. // Generate a list of benchmarks matching the specified --benchmark_filter flag
  231. // and if --benchmark_list_tests is specified return after printing the name
  232. // of each matching benchmark. Otherwise run each matching benchmark and
  233. // report the results.
  234. //
  235. // The second and third overload use the specified 'display_reporter' and
  236. // 'file_reporter' respectively. 'file_reporter' will write to the file
  237. // specified
  238. // by '--benchmark_output'. If '--benchmark_output' is not given the
  239. // 'file_reporter' is ignored.
  240. //
  241. // RETURNS: The number of matching benchmarks.
  242. size_t RunSpecifiedBenchmarks();
  243. size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter);
  244. size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter,
  245. BenchmarkReporter* file_reporter);
  246. // Register a MemoryManager instance that will be used to collect and report
  247. // allocation measurements for benchmark runs.
  248. void RegisterMemoryManager(MemoryManager* memory_manager);
  249. namespace internal {
  250. class Benchmark;
  251. class BenchmarkImp;
  252. class BenchmarkFamilies;
  253. void UseCharPointer(char const volatile*);
  254. // Take ownership of the pointer and register the benchmark. Return the
  255. // registered benchmark.
  256. Benchmark* RegisterBenchmarkInternal(Benchmark*);
  257. // Ensure that the standard streams are properly initialized in every TU.
  258. int InitializeStreams();
  259. BENCHMARK_UNUSED static int stream_init_anchor = InitializeStreams();
  260. } // namespace internal
  261. #if (!defined(__GNUC__) && !defined(__clang__)) || defined(__pnacl__) || \
  262. defined(__EMSCRIPTEN__)
  263. #define BENCHMARK_HAS_NO_INLINE_ASSEMBLY
  264. #endif
  265. // The DoNotOptimize(...) function can be used to prevent a value or
  266. // expression from being optimized away by the compiler. This function is
  267. // intended to add little to no overhead.
  268. // See: https://youtu.be/nXaxk27zwlk?t=2441
  269. #ifndef BENCHMARK_HAS_NO_INLINE_ASSEMBLY
  270. template <class Tp>
  271. inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) {
  272. asm volatile("" : : "r,m"(value) : "memory");
  273. }
  274. template <class Tp>
  275. inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp& value) {
  276. #if defined(__clang__)
  277. asm volatile("" : "+r,m"(value) : : "memory");
  278. #else
  279. asm volatile("" : "+m,r"(value) : : "memory");
  280. #endif
  281. }
  282. // Force the compiler to flush pending writes to global memory. Acts as an
  283. // effective read/write barrier
  284. inline BENCHMARK_ALWAYS_INLINE void ClobberMemory() {
  285. asm volatile("" : : : "memory");
  286. }
  287. #elif defined(_MSC_VER)
  288. template <class Tp>
  289. inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) {
  290. internal::UseCharPointer(&reinterpret_cast<char const volatile&>(value));
  291. _ReadWriteBarrier();
  292. }
  293. inline BENCHMARK_ALWAYS_INLINE void ClobberMemory() { _ReadWriteBarrier(); }
  294. #else
  295. template <class Tp>
  296. inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) {
  297. internal::UseCharPointer(&reinterpret_cast<char const volatile&>(value));
  298. }
  299. // FIXME Add ClobberMemory() for non-gnu and non-msvc compilers
  300. #endif
  301. // This class is used for user-defined counters.
  302. class Counter {
  303. public:
  304. enum Flags {
  305. kDefaults = 0,
  306. // Mark the counter as a rate. It will be presented divided
  307. // by the duration of the benchmark.
  308. kIsRate = 1U << 0U,
  309. // Mark the counter as a thread-average quantity. It will be
  310. // presented divided by the number of threads.
  311. kAvgThreads = 1U << 1U,
  312. // Mark the counter as a thread-average rate. See above.
  313. kAvgThreadsRate = kIsRate | kAvgThreads,
  314. // Mark the counter as a constant value, valid/same for *every* iteration.
  315. // When reporting, it will be *multiplied* by the iteration count.
  316. kIsIterationInvariant = 1U << 2U,
  317. // Mark the counter as a constant rate.
  318. // When reporting, it will be *multiplied* by the iteration count
  319. // and then divided by the duration of the benchmark.
  320. kIsIterationInvariantRate = kIsRate | kIsIterationInvariant,
  321. // Mark the counter as a iteration-average quantity.
  322. // It will be presented divided by the number of iterations.
  323. kAvgIterations = 1U << 3U,
  324. // Mark the counter as a iteration-average rate. See above.
  325. kAvgIterationsRate = kIsRate | kAvgIterations
  326. };
  327. enum OneK {
  328. // 1'000 items per 1k
  329. kIs1000 = 1000,
  330. // 1'024 items per 1k
  331. kIs1024 = 1024
  332. };
  333. double value;
  334. Flags flags;
  335. OneK oneK;
  336. BENCHMARK_ALWAYS_INLINE
  337. Counter(double v = 0., Flags f = kDefaults, OneK k = kIs1000)
  338. : value(v), flags(f), oneK(k) {}
  339. BENCHMARK_ALWAYS_INLINE operator double const&() const { return value; }
  340. BENCHMARK_ALWAYS_INLINE operator double&() { return value; }
  341. };
  342. // A helper for user code to create unforeseen combinations of Flags, without
  343. // having to do this cast manually each time, or providing this operator.
  344. Counter::Flags inline operator|(const Counter::Flags& LHS,
  345. const Counter::Flags& RHS) {
  346. return static_cast<Counter::Flags>(static_cast<int>(LHS) |
  347. static_cast<int>(RHS));
  348. }
  349. // This is the container for the user-defined counters.
  350. typedef std::map<std::string, Counter> UserCounters;
  351. // TimeUnit is passed to a benchmark in order to specify the order of magnitude
  352. // for the measured time.
  353. enum TimeUnit { kNanosecond, kMicrosecond, kMillisecond };
  354. // BigO is passed to a benchmark in order to specify the asymptotic
  355. // computational
  356. // complexity for the benchmark. In case oAuto is selected, complexity will be
  357. // calculated automatically to the best fit.
  358. enum BigO { oNone, o1, oN, oNSquared, oNCubed, oLogN, oNLogN, oAuto, oLambda };
  359. // BigOFunc is passed to a benchmark in order to specify the asymptotic
  360. // computational complexity for the benchmark.
  361. typedef double(BigOFunc)(int64_t);
  362. // StatisticsFunc is passed to a benchmark in order to compute some descriptive
  363. // statistics over all the measurements of some type
  364. typedef double(StatisticsFunc)(const std::vector<double>&);
  365. struct Statistics {
  366. std::string name_;
  367. StatisticsFunc* compute_;
  368. Statistics(const std::string& name, StatisticsFunc* compute)
  369. : name_(name), compute_(compute) {}
  370. };
  371. namespace internal {
  372. struct BenchmarkInstance;
  373. class ThreadTimer;
  374. class ThreadManager;
  375. enum AggregationReportMode
  376. #if defined(BENCHMARK_HAS_CXX11)
  377. : unsigned
  378. #else
  379. #endif
  380. {
  381. // The mode has not been manually specified
  382. ARM_Unspecified = 0,
  383. // The mode is user-specified.
  384. // This may or may not be set when the following bit-flags are set.
  385. ARM_Default = 1U << 0U,
  386. // File reporter should only output aggregates.
  387. ARM_FileReportAggregatesOnly = 1U << 1U,
  388. // Display reporter should only output aggregates
  389. ARM_DisplayReportAggregatesOnly = 1U << 2U,
  390. // Both reporters should only display aggregates.
  391. ARM_ReportAggregatesOnly =
  392. ARM_FileReportAggregatesOnly | ARM_DisplayReportAggregatesOnly
  393. };
  394. } // namespace internal
  395. // State is passed to a running Benchmark and contains state for the
  396. // benchmark to use.
  397. class State {
  398. public:
  399. struct StateIterator;
  400. friend struct StateIterator;
  401. // Returns iterators used to run each iteration of a benchmark using a
  402. // C++11 ranged-based for loop. These functions should not be called directly.
  403. //
  404. // REQUIRES: The benchmark has not started running yet. Neither begin nor end
  405. // have been called previously.
  406. //
  407. // NOTE: KeepRunning may not be used after calling either of these functions.
  408. BENCHMARK_ALWAYS_INLINE StateIterator begin();
  409. BENCHMARK_ALWAYS_INLINE StateIterator end();
  410. // Returns true if the benchmark should continue through another iteration.
  411. // NOTE: A benchmark may not return from the test until KeepRunning() has
  412. // returned false.
  413. bool KeepRunning();
  414. // Returns true iff the benchmark should run n more iterations.
  415. // REQUIRES: 'n' > 0.
  416. // NOTE: A benchmark must not return from the test until KeepRunningBatch()
  417. // has returned false.
  418. // NOTE: KeepRunningBatch() may overshoot by up to 'n' iterations.
  419. //
  420. // Intended usage:
  421. // while (state.KeepRunningBatch(1000)) {
  422. // // process 1000 elements
  423. // }
  424. bool KeepRunningBatch(size_t n);
  425. // REQUIRES: timer is running and 'SkipWithError(...)' has not been called
  426. // by the current thread.
  427. // Stop the benchmark timer. If not called, the timer will be
  428. // automatically stopped after the last iteration of the benchmark loop.
  429. //
  430. // For threaded benchmarks the PauseTiming() function only pauses the timing
  431. // for the current thread.
  432. //
  433. // NOTE: The "real time" measurement is per-thread. If different threads
  434. // report different measurements the largest one is reported.
  435. //
  436. // NOTE: PauseTiming()/ResumeTiming() are relatively
  437. // heavyweight, and so their use should generally be avoided
  438. // within each benchmark iteration, if possible.
  439. void PauseTiming();
  440. // REQUIRES: timer is not running and 'SkipWithError(...)' has not been called
  441. // by the current thread.
  442. // Start the benchmark timer. The timer is NOT running on entrance to the
  443. // benchmark function. It begins running after control flow enters the
  444. // benchmark loop.
  445. //
  446. // NOTE: PauseTiming()/ResumeTiming() are relatively
  447. // heavyweight, and so their use should generally be avoided
  448. // within each benchmark iteration, if possible.
  449. void ResumeTiming();
  450. // REQUIRES: 'SkipWithError(...)' has not been called previously by the
  451. // current thread.
  452. // Report the benchmark as resulting in an error with the specified 'msg'.
  453. // After this call the user may explicitly 'return' from the benchmark.
  454. //
  455. // If the ranged-for style of benchmark loop is used, the user must explicitly
  456. // break from the loop, otherwise all future iterations will be run.
  457. // If the 'KeepRunning()' loop is used the current thread will automatically
  458. // exit the loop at the end of the current iteration.
  459. //
  460. // For threaded benchmarks only the current thread stops executing and future
  461. // calls to `KeepRunning()` will block until all threads have completed
  462. // the `KeepRunning()` loop. If multiple threads report an error only the
  463. // first error message is used.
  464. //
  465. // NOTE: Calling 'SkipWithError(...)' does not cause the benchmark to exit
  466. // the current scope immediately. If the function is called from within
  467. // the 'KeepRunning()' loop the current iteration will finish. It is the users
  468. // responsibility to exit the scope as needed.
  469. void SkipWithError(const char* msg);
  470. // REQUIRES: called exactly once per iteration of the benchmarking loop.
  471. // Set the manually measured time for this benchmark iteration, which
  472. // is used instead of automatically measured time if UseManualTime() was
  473. // specified.
  474. //
  475. // For threaded benchmarks the final value will be set to the largest
  476. // reported values.
  477. void SetIterationTime(double seconds);
  478. // Set the number of bytes processed by the current benchmark
  479. // execution. This routine is typically called once at the end of a
  480. // throughput oriented benchmark.
  481. //
  482. // REQUIRES: a benchmark has exited its benchmarking loop.
  483. BENCHMARK_ALWAYS_INLINE
  484. void SetBytesProcessed(int64_t bytes) {
  485. counters["bytes_per_second"] =
  486. Counter(static_cast<double>(bytes), Counter::kIsRate, Counter::kIs1024);
  487. }
  488. BENCHMARK_ALWAYS_INLINE
  489. int64_t bytes_processed() const {
  490. if (counters.find("bytes_per_second") != counters.end())
  491. return static_cast<int64_t>(counters.at("bytes_per_second"));
  492. return 0;
  493. }
  494. // If this routine is called with complexity_n > 0 and complexity report is
  495. // requested for the
  496. // family benchmark, then current benchmark will be part of the computation
  497. // and complexity_n will
  498. // represent the length of N.
  499. BENCHMARK_ALWAYS_INLINE
  500. void SetComplexityN(int64_t complexity_n) { complexity_n_ = complexity_n; }
  501. BENCHMARK_ALWAYS_INLINE
  502. int64_t complexity_length_n() { return complexity_n_; }
  503. // If this routine is called with items > 0, then an items/s
  504. // label is printed on the benchmark report line for the currently
  505. // executing benchmark. It is typically called at the end of a processing
  506. // benchmark where a processing items/second output is desired.
  507. //
  508. // REQUIRES: a benchmark has exited its benchmarking loop.
  509. BENCHMARK_ALWAYS_INLINE
  510. void SetItemsProcessed(int64_t items) {
  511. counters["items_per_second"] =
  512. Counter(static_cast<double>(items), benchmark::Counter::kIsRate);
  513. }
  514. BENCHMARK_ALWAYS_INLINE
  515. int64_t items_processed() const {
  516. if (counters.find("items_per_second") != counters.end())
  517. return static_cast<int64_t>(counters.at("items_per_second"));
  518. return 0;
  519. }
  520. // If this routine is called, the specified label is printed at the
  521. // end of the benchmark report line for the currently executing
  522. // benchmark. Example:
  523. // static void BM_Compress(benchmark::State& state) {
  524. // ...
  525. // double compress = input_size / output_size;
  526. // state.SetLabel(StrFormat("compress:%.1f%%", 100.0*compression));
  527. // }
  528. // Produces output that looks like:
  529. // BM_Compress 50 50 14115038 compress:27.3%
  530. //
  531. // REQUIRES: a benchmark has exited its benchmarking loop.
  532. void SetLabel(const char* label);
  533. void BENCHMARK_ALWAYS_INLINE SetLabel(const std::string& str) {
  534. this->SetLabel(str.c_str());
  535. }
  536. // Range arguments for this run. CHECKs if the argument has been set.
  537. BENCHMARK_ALWAYS_INLINE
  538. int64_t range(std::size_t pos = 0) const {
  539. assert(range_.size() > pos);
  540. return range_[pos];
  541. }
  542. BENCHMARK_DEPRECATED_MSG("use 'range(0)' instead")
  543. int64_t range_x() const { return range(0); }
  544. BENCHMARK_DEPRECATED_MSG("use 'range(1)' instead")
  545. int64_t range_y() const { return range(1); }
  546. BENCHMARK_ALWAYS_INLINE
  547. size_t iterations() const {
  548. if (BENCHMARK_BUILTIN_EXPECT(!started_, false)) {
  549. return 0;
  550. }
  551. return max_iterations - total_iterations_ + batch_leftover_;
  552. }
  553. private
  554. : // items we expect on the first cache line (ie 64 bytes of the struct)
  555. // When total_iterations_ is 0, KeepRunning() and friends will return false.
  556. // May be larger than max_iterations.
  557. size_t total_iterations_;
  558. // When using KeepRunningBatch(), batch_leftover_ holds the number of
  559. // iterations beyond max_iters that were run. Used to track
  560. // completed_iterations_ accurately.
  561. size_t batch_leftover_;
  562. public:
  563. const size_t max_iterations;
  564. private:
  565. bool started_;
  566. bool finished_;
  567. bool error_occurred_;
  568. private: // items we don't need on the first cache line
  569. std::vector<int64_t> range_;
  570. int64_t complexity_n_;
  571. public:
  572. // Container for user-defined counters.
  573. UserCounters counters;
  574. // Index of the executing thread. Values from [0, threads).
  575. const int thread_index;
  576. // Number of threads concurrently executing the benchmark.
  577. const int threads;
  578. private:
  579. State(size_t max_iters, const std::vector<int64_t>& ranges, int thread_i,
  580. int n_threads, internal::ThreadTimer* timer,
  581. internal::ThreadManager* manager);
  582. void StartKeepRunning();
  583. // Implementation of KeepRunning() and KeepRunningBatch().
  584. // is_batch must be true unless n is 1.
  585. bool KeepRunningInternal(size_t n, bool is_batch);
  586. void FinishKeepRunning();
  587. internal::ThreadTimer* timer_;
  588. internal::ThreadManager* manager_;
  589. friend struct internal::BenchmarkInstance;
  590. };
  591. inline BENCHMARK_ALWAYS_INLINE bool State::KeepRunning() {
  592. return KeepRunningInternal(1, /*is_batch=*/false);
  593. }
  594. inline BENCHMARK_ALWAYS_INLINE bool State::KeepRunningBatch(size_t n) {
  595. return KeepRunningInternal(n, /*is_batch=*/true);
  596. }
  597. inline BENCHMARK_ALWAYS_INLINE bool State::KeepRunningInternal(size_t n,
  598. bool is_batch) {
  599. // total_iterations_ is set to 0 by the constructor, and always set to a
  600. // nonzero value by StartKepRunning().
  601. assert(n > 0);
  602. // n must be 1 unless is_batch is true.
  603. assert(is_batch || n == 1);
  604. if (BENCHMARK_BUILTIN_EXPECT(total_iterations_ >= n, true)) {
  605. total_iterations_ -= n;
  606. return true;
  607. }
  608. if (!started_) {
  609. StartKeepRunning();
  610. if (!error_occurred_ && total_iterations_ >= n) {
  611. total_iterations_ -= n;
  612. return true;
  613. }
  614. }
  615. // For non-batch runs, total_iterations_ must be 0 by now.
  616. if (is_batch && total_iterations_ != 0) {
  617. batch_leftover_ = n - total_iterations_;
  618. total_iterations_ = 0;
  619. return true;
  620. }
  621. FinishKeepRunning();
  622. return false;
  623. }
  624. struct State::StateIterator {
  625. struct BENCHMARK_UNUSED Value {};
  626. typedef std::forward_iterator_tag iterator_category;
  627. typedef Value value_type;
  628. typedef Value reference;
  629. typedef Value pointer;
  630. typedef std::ptrdiff_t difference_type;
  631. private:
  632. friend class State;
  633. BENCHMARK_ALWAYS_INLINE
  634. StateIterator() : cached_(0), parent_() {}
  635. BENCHMARK_ALWAYS_INLINE
  636. explicit StateIterator(State* st)
  637. : cached_(st->error_occurred_ ? 0 : st->max_iterations), parent_(st) {}
  638. public:
  639. BENCHMARK_ALWAYS_INLINE
  640. Value operator*() const { return Value(); }
  641. BENCHMARK_ALWAYS_INLINE
  642. StateIterator& operator++() {
  643. assert(cached_ > 0);
  644. --cached_;
  645. return *this;
  646. }
  647. BENCHMARK_ALWAYS_INLINE
  648. bool operator!=(StateIterator const&) const {
  649. if (BENCHMARK_BUILTIN_EXPECT(cached_ != 0, true)) return true;
  650. parent_->FinishKeepRunning();
  651. return false;
  652. }
  653. private:
  654. size_t cached_;
  655. State* const parent_;
  656. };
  657. inline BENCHMARK_ALWAYS_INLINE State::StateIterator State::begin() {
  658. return StateIterator(this);
  659. }
  660. inline BENCHMARK_ALWAYS_INLINE State::StateIterator State::end() {
  661. StartKeepRunning();
  662. return StateIterator();
  663. }
  664. namespace internal {
  665. typedef void(Function)(State&);
  666. // ------------------------------------------------------
  667. // Benchmark registration object. The BENCHMARK() macro expands
  668. // into an internal::Benchmark* object. Various methods can
  669. // be called on this object to change the properties of the benchmark.
  670. // Each method returns "this" so that multiple method calls can
  671. // chained into one expression.
  672. class Benchmark {
  673. public:
  674. virtual ~Benchmark();
  675. // Note: the following methods all return "this" so that multiple
  676. // method calls can be chained together in one expression.
  677. // Run this benchmark once with "x" as the extra argument passed
  678. // to the function.
  679. // REQUIRES: The function passed to the constructor must accept an arg1.
  680. Benchmark* Arg(int64_t x);
  681. // Run this benchmark with the given time unit for the generated output report
  682. Benchmark* Unit(TimeUnit unit);
  683. // Run this benchmark once for a number of values picked from the
  684. // range [start..limit]. (start and limit are always picked.)
  685. // REQUIRES: The function passed to the constructor must accept an arg1.
  686. Benchmark* Range(int64_t start, int64_t limit);
  687. // Run this benchmark once for all values in the range [start..limit] with
  688. // specific step
  689. // REQUIRES: The function passed to the constructor must accept an arg1.
  690. Benchmark* DenseRange(int64_t start, int64_t limit, int step = 1);
  691. // Run this benchmark once with "args" as the extra arguments passed
  692. // to the function.
  693. // REQUIRES: The function passed to the constructor must accept arg1, arg2 ...
  694. Benchmark* Args(const std::vector<int64_t>& args);
  695. // Equivalent to Args({x, y})
  696. // NOTE: This is a legacy C++03 interface provided for compatibility only.
  697. // New code should use 'Args'.
  698. Benchmark* ArgPair(int64_t x, int64_t y) {
  699. std::vector<int64_t> args;
  700. args.push_back(x);
  701. args.push_back(y);
  702. return Args(args);
  703. }
  704. // Run this benchmark once for a number of values picked from the
  705. // ranges [start..limit]. (starts and limits are always picked.)
  706. // REQUIRES: The function passed to the constructor must accept arg1, arg2 ...
  707. Benchmark* Ranges(const std::vector<std::pair<int64_t, int64_t> >& ranges);
  708. // Equivalent to ArgNames({name})
  709. Benchmark* ArgName(const std::string& name);
  710. // Set the argument names to display in the benchmark name. If not called,
  711. // only argument values will be shown.
  712. Benchmark* ArgNames(const std::vector<std::string>& names);
  713. // Equivalent to Ranges({{lo1, hi1}, {lo2, hi2}}).
  714. // NOTE: This is a legacy C++03 interface provided for compatibility only.
  715. // New code should use 'Ranges'.
  716. Benchmark* RangePair(int64_t lo1, int64_t hi1, int64_t lo2, int64_t hi2) {
  717. std::vector<std::pair<int64_t, int64_t> > ranges;
  718. ranges.push_back(std::make_pair(lo1, hi1));
  719. ranges.push_back(std::make_pair(lo2, hi2));
  720. return Ranges(ranges);
  721. }
  722. // Pass this benchmark object to *func, which can customize
  723. // the benchmark by calling various methods like Arg, Args,
  724. // Threads, etc.
  725. Benchmark* Apply(void (*func)(Benchmark* benchmark));
  726. // Set the range multiplier for non-dense range. If not called, the range
  727. // multiplier kRangeMultiplier will be used.
  728. Benchmark* RangeMultiplier(int multiplier);
  729. // Set the minimum amount of time to use when running this benchmark. This
  730. // option overrides the `benchmark_min_time` flag.
  731. // REQUIRES: `t > 0` and `Iterations` has not been called on this benchmark.
  732. Benchmark* MinTime(double t);
  733. // Specify the amount of iterations that should be run by this benchmark.
  734. // REQUIRES: 'n > 0' and `MinTime` has not been called on this benchmark.
  735. //
  736. // NOTE: This function should only be used when *exact* iteration control is
  737. // needed and never to control or limit how long a benchmark runs, where
  738. // `--benchmark_min_time=N` or `MinTime(...)` should be used instead.
  739. Benchmark* Iterations(size_t n);
  740. // Specify the amount of times to repeat this benchmark. This option overrides
  741. // the `benchmark_repetitions` flag.
  742. // REQUIRES: `n > 0`
  743. Benchmark* Repetitions(int n);
  744. // Specify if each repetition of the benchmark should be reported separately
  745. // or if only the final statistics should be reported. If the benchmark
  746. // is not repeated then the single result is always reported.
  747. // Applies to *ALL* reporters (display and file).
  748. Benchmark* ReportAggregatesOnly(bool value = true);
  749. // Same as ReportAggregatesOnly(), but applies to display reporter only.
  750. Benchmark* DisplayAggregatesOnly(bool value = true);
  751. // If a particular benchmark is I/O bound, runs multiple threads internally or
  752. // if for some reason CPU timings are not representative, call this method. If
  753. // called, the elapsed time will be used to control how many iterations are
  754. // run, and in the printing of items/second or MB/seconds values. If not
  755. // called, the cpu time used by the benchmark will be used.
  756. Benchmark* UseRealTime();
  757. // If a benchmark must measure time manually (e.g. if GPU execution time is
  758. // being
  759. // measured), call this method. If called, each benchmark iteration should
  760. // call
  761. // SetIterationTime(seconds) to report the measured time, which will be used
  762. // to control how many iterations are run, and in the printing of items/second
  763. // or MB/second values.
  764. Benchmark* UseManualTime();
  765. // Set the asymptotic computational complexity for the benchmark. If called
  766. // the asymptotic computational complexity will be shown on the output.
  767. Benchmark* Complexity(BigO complexity = benchmark::oAuto);
  768. // Set the asymptotic computational complexity for the benchmark. If called
  769. // the asymptotic computational complexity will be shown on the output.
  770. Benchmark* Complexity(BigOFunc* complexity);
  771. // Add this statistics to be computed over all the values of benchmark run
  772. Benchmark* ComputeStatistics(std::string name, StatisticsFunc* statistics);
  773. // Support for running multiple copies of the same benchmark concurrently
  774. // in multiple threads. This may be useful when measuring the scaling
  775. // of some piece of code.
  776. // Run one instance of this benchmark concurrently in t threads.
  777. Benchmark* Threads(int t);
  778. // Pick a set of values T from [min_threads,max_threads].
  779. // min_threads and max_threads are always included in T. Run this
  780. // benchmark once for each value in T. The benchmark run for a
  781. // particular value t consists of t threads running the benchmark
  782. // function concurrently. For example, consider:
  783. // BENCHMARK(Foo)->ThreadRange(1,16);
  784. // This will run the following benchmarks:
  785. // Foo in 1 thread
  786. // Foo in 2 threads
  787. // Foo in 4 threads
  788. // Foo in 8 threads
  789. // Foo in 16 threads
  790. Benchmark* ThreadRange(int min_threads, int max_threads);
  791. // For each value n in the range, run this benchmark once using n threads.
  792. // min_threads and max_threads are always included in the range.
  793. // stride specifies the increment. E.g. DenseThreadRange(1, 8, 3) starts
  794. // a benchmark with 1, 4, 7 and 8 threads.
  795. Benchmark* DenseThreadRange(int min_threads, int max_threads, int stride = 1);
  796. // Equivalent to ThreadRange(NumCPUs(), NumCPUs())
  797. Benchmark* ThreadPerCpu();
  798. virtual void Run(State& state) = 0;
  799. protected:
  800. explicit Benchmark(const char* name);
  801. Benchmark(Benchmark const&);
  802. void SetName(const char* name);
  803. int ArgsCnt() const;
  804. private:
  805. friend class BenchmarkFamilies;
  806. std::string name_;
  807. AggregationReportMode aggregation_report_mode_;
  808. std::vector<std::string> arg_names_; // Args for all benchmark runs
  809. std::vector<std::vector<int64_t> > args_; // Args for all benchmark runs
  810. TimeUnit time_unit_;
  811. int range_multiplier_;
  812. double min_time_;
  813. size_t iterations_;
  814. int repetitions_;
  815. bool use_real_time_;
  816. bool use_manual_time_;
  817. BigO complexity_;
  818. BigOFunc* complexity_lambda_;
  819. std::vector<Statistics> statistics_;
  820. std::vector<int> thread_counts_;
  821. Benchmark& operator=(Benchmark const&);
  822. };
  823. } // namespace internal
  824. // Create and register a benchmark with the specified 'name' that invokes
  825. // the specified functor 'fn'.
  826. //
  827. // RETURNS: A pointer to the registered benchmark.
  828. internal::Benchmark* RegisterBenchmark(const char* name,
  829. internal::Function* fn);
  830. #if defined(BENCHMARK_HAS_CXX11)
  831. template <class Lambda>
  832. internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn);
  833. #endif
  834. // Remove all registered benchmarks. All pointers to previously registered
  835. // benchmarks are invalidated.
  836. void ClearRegisteredBenchmarks();
  837. namespace internal {
  838. // The class used to hold all Benchmarks created from static function.
  839. // (ie those created using the BENCHMARK(...) macros.
  840. class FunctionBenchmark : public Benchmark {
  841. public:
  842. FunctionBenchmark(const char* name, Function* func)
  843. : Benchmark(name), func_(func) {}
  844. virtual void Run(State& st);
  845. private:
  846. Function* func_;
  847. };
  848. #ifdef BENCHMARK_HAS_CXX11
  849. template <class Lambda>
  850. class LambdaBenchmark : public Benchmark {
  851. public:
  852. virtual void Run(State& st) { lambda_(st); }
  853. private:
  854. template <class OLambda>
  855. LambdaBenchmark(const char* name, OLambda&& lam)
  856. : Benchmark(name), lambda_(std::forward<OLambda>(lam)) {}
  857. LambdaBenchmark(LambdaBenchmark const&) = delete;
  858. private:
  859. template <class Lam>
  860. friend Benchmark* ::benchmark::RegisterBenchmark(const char*, Lam&&);
  861. Lambda lambda_;
  862. };
  863. #endif
  864. } // namespace internal
  865. inline internal::Benchmark* RegisterBenchmark(const char* name,
  866. internal::Function* fn) {
  867. return internal::RegisterBenchmarkInternal(
  868. ::new internal::FunctionBenchmark(name, fn));
  869. }
  870. #ifdef BENCHMARK_HAS_CXX11
  871. template <class Lambda>
  872. internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn) {
  873. using BenchType =
  874. internal::LambdaBenchmark<typename std::decay<Lambda>::type>;
  875. return internal::RegisterBenchmarkInternal(
  876. ::new BenchType(name, std::forward<Lambda>(fn)));
  877. }
  878. #endif
  879. #if defined(BENCHMARK_HAS_CXX11) && \
  880. (!defined(BENCHMARK_GCC_VERSION) || BENCHMARK_GCC_VERSION >= 409)
  881. template <class Lambda, class... Args>
  882. internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn,
  883. Args&&... args) {
  884. return benchmark::RegisterBenchmark(
  885. name, [=](benchmark::State& st) { fn(st, args...); });
  886. }
  887. #else
  888. #define BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK
  889. #endif
  890. // The base class for all fixture tests.
  891. class Fixture : public internal::Benchmark {
  892. public:
  893. Fixture() : internal::Benchmark("") {}
  894. virtual void Run(State& st) {
  895. this->SetUp(st);
  896. this->BenchmarkCase(st);
  897. this->TearDown(st);
  898. }
  899. // These will be deprecated ...
  900. virtual void SetUp(const State&) {}
  901. virtual void TearDown(const State&) {}
  902. // ... In favor of these.
  903. virtual void SetUp(State& st) { SetUp(const_cast<const State&>(st)); }
  904. virtual void TearDown(State& st) { TearDown(const_cast<const State&>(st)); }
  905. protected:
  906. virtual void BenchmarkCase(State&) = 0;
  907. };
  908. } // namespace benchmark
  909. // ------------------------------------------------------
  910. // Macro to register benchmarks
  911. // Check that __COUNTER__ is defined and that __COUNTER__ increases by 1
  912. // every time it is expanded. X + 1 == X + 0 is used in case X is defined to be
  913. // empty. If X is empty the expression becomes (+1 == +0).
  914. #if defined(__COUNTER__) && (__COUNTER__ + 1 == __COUNTER__ + 0)
  915. #define BENCHMARK_PRIVATE_UNIQUE_ID __COUNTER__
  916. #else
  917. #define BENCHMARK_PRIVATE_UNIQUE_ID __LINE__
  918. #endif
  919. // Helpers for generating unique variable names
  920. #define BENCHMARK_PRIVATE_NAME(n) \
  921. BENCHMARK_PRIVATE_CONCAT(_benchmark_, BENCHMARK_PRIVATE_UNIQUE_ID, n)
  922. #define BENCHMARK_PRIVATE_CONCAT(a, b, c) BENCHMARK_PRIVATE_CONCAT2(a, b, c)
  923. #define BENCHMARK_PRIVATE_CONCAT2(a, b, c) a##b##c
  924. #define BENCHMARK_PRIVATE_DECLARE(n) \
  925. static ::benchmark::internal::Benchmark* BENCHMARK_PRIVATE_NAME(n) \
  926. BENCHMARK_UNUSED
  927. #define BENCHMARK(n) \
  928. BENCHMARK_PRIVATE_DECLARE(n) = \
  929. (::benchmark::internal::RegisterBenchmarkInternal( \
  930. new ::benchmark::internal::FunctionBenchmark(#n, n)))
  931. // Old-style macros
  932. #define BENCHMARK_WITH_ARG(n, a) BENCHMARK(n)->Arg((a))
  933. #define BENCHMARK_WITH_ARG2(n, a1, a2) BENCHMARK(n)->Args({(a1), (a2)})
  934. #define BENCHMARK_WITH_UNIT(n, t) BENCHMARK(n)->Unit((t))
  935. #define BENCHMARK_RANGE(n, lo, hi) BENCHMARK(n)->Range((lo), (hi))
  936. #define BENCHMARK_RANGE2(n, l1, h1, l2, h2) \
  937. BENCHMARK(n)->RangePair({{(l1), (h1)}, {(l2), (h2)}})
  938. #ifdef BENCHMARK_HAS_CXX11
  939. // Register a benchmark which invokes the function specified by `func`
  940. // with the additional arguments specified by `...`.
  941. //
  942. // For example:
  943. //
  944. // template <class ...ExtraArgs>`
  945. // void BM_takes_args(benchmark::State& state, ExtraArgs&&... extra_args) {
  946. // [...]
  947. //}
  948. // /* Registers a benchmark named "BM_takes_args/int_string_test` */
  949. // BENCHMARK_CAPTURE(BM_takes_args, int_string_test, 42, std::string("abc"));
  950. #define BENCHMARK_CAPTURE(func, test_case_name, ...) \
  951. BENCHMARK_PRIVATE_DECLARE(func) = \
  952. (::benchmark::internal::RegisterBenchmarkInternal( \
  953. new ::benchmark::internal::FunctionBenchmark( \
  954. #func "/" #test_case_name, \
  955. [](::benchmark::State& st) { func(st, __VA_ARGS__); })))
  956. #endif // BENCHMARK_HAS_CXX11
  957. // This will register a benchmark for a templatized function. For example:
  958. //
  959. // template<int arg>
  960. // void BM_Foo(int iters);
  961. //
  962. // BENCHMARK_TEMPLATE(BM_Foo, 1);
  963. //
  964. // will register BM_Foo<1> as a benchmark.
  965. #define BENCHMARK_TEMPLATE1(n, a) \
  966. BENCHMARK_PRIVATE_DECLARE(n) = \
  967. (::benchmark::internal::RegisterBenchmarkInternal( \
  968. new ::benchmark::internal::FunctionBenchmark(#n "<" #a ">", n<a>)))
  969. #define BENCHMARK_TEMPLATE2(n, a, b) \
  970. BENCHMARK_PRIVATE_DECLARE(n) = \
  971. (::benchmark::internal::RegisterBenchmarkInternal( \
  972. new ::benchmark::internal::FunctionBenchmark(#n "<" #a "," #b ">", \
  973. n<a, b>)))
  974. #ifdef BENCHMARK_HAS_CXX11
  975. #define BENCHMARK_TEMPLATE(n, ...) \
  976. BENCHMARK_PRIVATE_DECLARE(n) = \
  977. (::benchmark::internal::RegisterBenchmarkInternal( \
  978. new ::benchmark::internal::FunctionBenchmark( \
  979. #n "<" #__VA_ARGS__ ">", n<__VA_ARGS__>)))
  980. #else
  981. #define BENCHMARK_TEMPLATE(n, a) BENCHMARK_TEMPLATE1(n, a)
  982. #endif
  983. #define BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \
  984. class BaseClass##_##Method##_Benchmark : public BaseClass { \
  985. public: \
  986. BaseClass##_##Method##_Benchmark() : BaseClass() { \
  987. this->SetName(#BaseClass "/" #Method); \
  988. } \
  989. \
  990. protected: \
  991. virtual void BenchmarkCase(::benchmark::State&); \
  992. };
  993. #define BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \
  994. class BaseClass##_##Method##_Benchmark : public BaseClass<a> { \
  995. public: \
  996. BaseClass##_##Method##_Benchmark() : BaseClass<a>() { \
  997. this->SetName(#BaseClass "<" #a ">/" #Method); \
  998. } \
  999. \
  1000. protected: \
  1001. virtual void BenchmarkCase(::benchmark::State&); \
  1002. };
  1003. #define BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \
  1004. class BaseClass##_##Method##_Benchmark : public BaseClass<a, b> { \
  1005. public: \
  1006. BaseClass##_##Method##_Benchmark() : BaseClass<a, b>() { \
  1007. this->SetName(#BaseClass "<" #a "," #b ">/" #Method); \
  1008. } \
  1009. \
  1010. protected: \
  1011. virtual void BenchmarkCase(::benchmark::State&); \
  1012. };
  1013. #ifdef BENCHMARK_HAS_CXX11
  1014. #define BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, ...) \
  1015. class BaseClass##_##Method##_Benchmark : public BaseClass<__VA_ARGS__> { \
  1016. public: \
  1017. BaseClass##_##Method##_Benchmark() : BaseClass<__VA_ARGS__>() { \
  1018. this->SetName(#BaseClass "<" #__VA_ARGS__ ">/" #Method); \
  1019. } \
  1020. \
  1021. protected: \
  1022. virtual void BenchmarkCase(::benchmark::State&); \
  1023. };
  1024. #else
  1025. #define BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(n, a) \
  1026. BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(n, a)
  1027. #endif
  1028. #define BENCHMARK_DEFINE_F(BaseClass, Method) \
  1029. BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \
  1030. void BaseClass##_##Method##_Benchmark::BenchmarkCase
  1031. #define BENCHMARK_TEMPLATE1_DEFINE_F(BaseClass, Method, a) \
  1032. BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \
  1033. void BaseClass##_##Method##_Benchmark::BenchmarkCase
  1034. #define BENCHMARK_TEMPLATE2_DEFINE_F(BaseClass, Method, a, b) \
  1035. BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \
  1036. void BaseClass##_##Method##_Benchmark::BenchmarkCase
  1037. #ifdef BENCHMARK_HAS_CXX11
  1038. #define BENCHMARK_TEMPLATE_DEFINE_F(BaseClass, Method, ...) \
  1039. BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, __VA_ARGS__) \
  1040. void BaseClass##_##Method##_Benchmark::BenchmarkCase
  1041. #else
  1042. #define BENCHMARK_TEMPLATE_DEFINE_F(BaseClass, Method, a) \
  1043. BENCHMARK_TEMPLATE1_DEFINE_F(BaseClass, Method, a)
  1044. #endif
  1045. #define BENCHMARK_REGISTER_F(BaseClass, Method) \
  1046. BENCHMARK_PRIVATE_REGISTER_F(BaseClass##_##Method##_Benchmark)
  1047. #define BENCHMARK_PRIVATE_REGISTER_F(TestName) \
  1048. BENCHMARK_PRIVATE_DECLARE(TestName) = \
  1049. (::benchmark::internal::RegisterBenchmarkInternal(new TestName()))
  1050. // This macro will define and register a benchmark within a fixture class.
  1051. #define BENCHMARK_F(BaseClass, Method) \
  1052. BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \
  1053. BENCHMARK_REGISTER_F(BaseClass, Method); \
  1054. void BaseClass##_##Method##_Benchmark::BenchmarkCase
  1055. #define BENCHMARK_TEMPLATE1_F(BaseClass, Method, a) \
  1056. BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \
  1057. BENCHMARK_REGISTER_F(BaseClass, Method); \
  1058. void BaseClass##_##Method##_Benchmark::BenchmarkCase
  1059. #define BENCHMARK_TEMPLATE2_F(BaseClass, Method, a, b) \
  1060. BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \
  1061. BENCHMARK_REGISTER_F(BaseClass, Method); \
  1062. void BaseClass##_##Method##_Benchmark::BenchmarkCase
  1063. #ifdef BENCHMARK_HAS_CXX11
  1064. #define BENCHMARK_TEMPLATE_F(BaseClass, Method, ...) \
  1065. BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, __VA_ARGS__) \
  1066. BENCHMARK_REGISTER_F(BaseClass, Method); \
  1067. void BaseClass##_##Method##_Benchmark::BenchmarkCase
  1068. #else
  1069. #define BENCHMARK_TEMPLATE_F(BaseClass, Method, a) \
  1070. BENCHMARK_TEMPLATE1_F(BaseClass, Method, a)
  1071. #endif
  1072. // Helper macro to create a main routine in a test that runs the benchmarks
  1073. #define BENCHMARK_MAIN() \
  1074. int main(int argc, char** argv) { \
  1075. ::benchmark::Initialize(&argc, argv); \
  1076. if (::benchmark::ReportUnrecognizedArguments(argc, argv)) return 1; \
  1077. ::benchmark::RunSpecifiedBenchmarks(); \
  1078. } \
  1079. int main(int, char**)
  1080. // ------------------------------------------------------
  1081. // Benchmark Reporters
  1082. namespace benchmark {
  1083. struct CPUInfo {
  1084. struct CacheInfo {
  1085. std::string type;
  1086. int level;
  1087. int size;
  1088. int num_sharing;
  1089. };
  1090. int num_cpus;
  1091. double cycles_per_second;
  1092. std::vector<CacheInfo> caches;
  1093. bool scaling_enabled;
  1094. std::vector<double> load_avg;
  1095. static const CPUInfo& Get();
  1096. private:
  1097. CPUInfo();
  1098. BENCHMARK_DISALLOW_COPY_AND_ASSIGN(CPUInfo);
  1099. };
  1100. //Adding Struct for System Information
  1101. struct SystemInfo {
  1102. std::string name;
  1103. static const SystemInfo& Get();
  1104. private:
  1105. SystemInfo();
  1106. BENCHMARK_DISALLOW_COPY_AND_ASSIGN(SystemInfo);
  1107. };
  1108. // Interface for custom benchmark result printers.
  1109. // By default, benchmark reports are printed to stdout. However an application
  1110. // can control the destination of the reports by calling
  1111. // RunSpecifiedBenchmarks and passing it a custom reporter object.
  1112. // The reporter object must implement the following interface.
  1113. class BenchmarkReporter {
  1114. public:
  1115. struct Context {
  1116. CPUInfo const& cpu_info;
  1117. SystemInfo const& sys_info;
  1118. // The number of chars in the longest benchmark name.
  1119. size_t name_field_width;
  1120. static const char* executable_name;
  1121. Context();
  1122. };
  1123. struct Run {
  1124. enum RunType { RT_Iteration, RT_Aggregate };
  1125. Run()
  1126. : run_type(RT_Iteration),
  1127. error_occurred(false),
  1128. iterations(1),
  1129. time_unit(kNanosecond),
  1130. real_accumulated_time(0),
  1131. cpu_accumulated_time(0),
  1132. max_heapbytes_used(0),
  1133. complexity(oNone),
  1134. complexity_lambda(),
  1135. complexity_n(0),
  1136. report_big_o(false),
  1137. report_rms(false),
  1138. counters(),
  1139. has_memory_result(false),
  1140. allocs_per_iter(0.0),
  1141. max_bytes_used(0) {}
  1142. std::string benchmark_name() const;
  1143. std::string run_name;
  1144. RunType run_type; // is this a measurement, or an aggregate?
  1145. std::string aggregate_name;
  1146. std::string report_label; // Empty if not set by benchmark.
  1147. bool error_occurred;
  1148. std::string error_message;
  1149. int64_t iterations;
  1150. TimeUnit time_unit;
  1151. double real_accumulated_time;
  1152. double cpu_accumulated_time;
  1153. // Return a value representing the real time per iteration in the unit
  1154. // specified by 'time_unit'.
  1155. // NOTE: If 'iterations' is zero the returned value represents the
  1156. // accumulated time.
  1157. double GetAdjustedRealTime() const;
  1158. // Return a value representing the cpu time per iteration in the unit
  1159. // specified by 'time_unit'.
  1160. // NOTE: If 'iterations' is zero the returned value represents the
  1161. // accumulated time.
  1162. double GetAdjustedCPUTime() const;
  1163. // This is set to 0.0 if memory tracing is not enabled.
  1164. double max_heapbytes_used;
  1165. // Keep track of arguments to compute asymptotic complexity
  1166. BigO complexity;
  1167. BigOFunc* complexity_lambda;
  1168. int64_t complexity_n;
  1169. // what statistics to compute from the measurements
  1170. const std::vector<Statistics>* statistics;
  1171. // Inform print function whether the current run is a complexity report
  1172. bool report_big_o;
  1173. bool report_rms;
  1174. UserCounters counters;
  1175. // Memory metrics.
  1176. bool has_memory_result;
  1177. double allocs_per_iter;
  1178. int64_t max_bytes_used;
  1179. };
  1180. // Construct a BenchmarkReporter with the output stream set to 'std::cout'
  1181. // and the error stream set to 'std::cerr'
  1182. BenchmarkReporter();
  1183. // Called once for every suite of benchmarks run.
  1184. // The parameter "context" contains information that the
  1185. // reporter may wish to use when generating its report, for example the
  1186. // platform under which the benchmarks are running. The benchmark run is
  1187. // never started if this function returns false, allowing the reporter
  1188. // to skip runs based on the context information.
  1189. virtual bool ReportContext(const Context& context) = 0;
  1190. // Called once for each group of benchmark runs, gives information about
  1191. // cpu-time and heap memory usage during the benchmark run. If the group
  1192. // of runs contained more than two entries then 'report' contains additional
  1193. // elements representing the mean and standard deviation of those runs.
  1194. // Additionally if this group of runs was the last in a family of benchmarks
  1195. // 'reports' contains additional entries representing the asymptotic
  1196. // complexity and RMS of that benchmark family.
  1197. virtual void ReportRuns(const std::vector<Run>& report) = 0;
  1198. // Called once and only once after ever group of benchmarks is run and
  1199. // reported.
  1200. virtual void Finalize() {}
  1201. // REQUIRES: The object referenced by 'out' is valid for the lifetime
  1202. // of the reporter.
  1203. void SetOutputStream(std::ostream* out) {
  1204. assert(out);
  1205. output_stream_ = out;
  1206. }
  1207. // REQUIRES: The object referenced by 'err' is valid for the lifetime
  1208. // of the reporter.
  1209. void SetErrorStream(std::ostream* err) {
  1210. assert(err);
  1211. error_stream_ = err;
  1212. }
  1213. std::ostream& GetOutputStream() const { return *output_stream_; }
  1214. std::ostream& GetErrorStream() const { return *error_stream_; }
  1215. virtual ~BenchmarkReporter();
  1216. // Write a human readable string to 'out' representing the specified
  1217. // 'context'.
  1218. // REQUIRES: 'out' is non-null.
  1219. static void PrintBasicContext(std::ostream* out, Context const& context);
  1220. private:
  1221. std::ostream* output_stream_;
  1222. std::ostream* error_stream_;
  1223. };
  1224. // Simple reporter that outputs benchmark data to the console. This is the
  1225. // default reporter used by RunSpecifiedBenchmarks().
  1226. class ConsoleReporter : public BenchmarkReporter {
  1227. public:
  1228. enum OutputOptions {
  1229. OO_None = 0,
  1230. OO_Color = 1,
  1231. OO_Tabular = 2,
  1232. OO_ColorTabular = OO_Color | OO_Tabular,
  1233. OO_Defaults = OO_ColorTabular
  1234. };
  1235. explicit ConsoleReporter(OutputOptions opts_ = OO_Defaults)
  1236. : output_options_(opts_),
  1237. name_field_width_(0),
  1238. prev_counters_(),
  1239. printed_header_(false) {}
  1240. virtual bool ReportContext(const Context& context);
  1241. virtual void ReportRuns(const std::vector<Run>& reports);
  1242. protected:
  1243. virtual void PrintRunData(const Run& report);
  1244. virtual void PrintHeader(const Run& report);
  1245. OutputOptions output_options_;
  1246. size_t name_field_width_;
  1247. UserCounters prev_counters_;
  1248. bool printed_header_;
  1249. };
  1250. class JSONReporter : public BenchmarkReporter {
  1251. public:
  1252. JSONReporter() : first_report_(true) {}
  1253. virtual bool ReportContext(const Context& context);
  1254. virtual void ReportRuns(const std::vector<Run>& reports);
  1255. virtual void Finalize();
  1256. private:
  1257. void PrintRunData(const Run& report);
  1258. bool first_report_;
  1259. };
  1260. class BENCHMARK_DEPRECATED_MSG("The CSV Reporter will be removed in a future release")
  1261. CSVReporter : public BenchmarkReporter {
  1262. public:
  1263. CSVReporter() : printed_header_(false) {}
  1264. virtual bool ReportContext(const Context& context);
  1265. virtual void ReportRuns(const std::vector<Run>& reports);
  1266. private:
  1267. void PrintRunData(const Run& report);
  1268. bool printed_header_;
  1269. std::set<std::string> user_counter_names_;
  1270. };
  1271. // If a MemoryManager is registered, it can be used to collect and report
  1272. // allocation metrics for a run of the benchmark.
  1273. class MemoryManager {
  1274. public:
  1275. struct Result {
  1276. Result() : num_allocs(0), max_bytes_used(0) {}
  1277. // The number of allocations made in total between Start and Stop.
  1278. int64_t num_allocs;
  1279. // The peak memory use between Start and Stop.
  1280. int64_t max_bytes_used;
  1281. };
  1282. virtual ~MemoryManager() {}
  1283. // Implement this to start recording allocation information.
  1284. virtual void Start() = 0;
  1285. // Implement this to stop recording and fill out the given Result structure.
  1286. virtual void Stop(Result* result) = 0;
  1287. };
  1288. inline const char* GetTimeUnitString(TimeUnit unit) {
  1289. switch (unit) {
  1290. case kMillisecond:
  1291. return "ms";
  1292. case kMicrosecond:
  1293. return "us";
  1294. case kNanosecond:
  1295. return "ns";
  1296. }
  1297. BENCHMARK_UNREACHABLE();
  1298. }
  1299. inline double GetTimeUnitMultiplier(TimeUnit unit) {
  1300. switch (unit) {
  1301. case kMillisecond:
  1302. return 1e3;
  1303. case kMicrosecond:
  1304. return 1e6;
  1305. case kNanosecond:
  1306. return 1e9;
  1307. }
  1308. BENCHMARK_UNREACHABLE();
  1309. }
  1310. } // namespace benchmark
  1311. #endif // BENCHMARK_BENCHMARK_H_