1 // Support for registering benchmarks for functions.
2 
3 /* Example usage:
4 // Define a function that executes the code to be measured a
5 // specified number of times:
6 static void BM_StringCreation(benchmark::State& state) {
7   while (state.KeepRunning())
8     std::string empty_string;
9 }
10 
11 // Register the function as a benchmark
12 BENCHMARK(BM_StringCreation);
13 
14 // Define another benchmark
15 static void BM_StringCopy(benchmark::State& state) {
16   std::string x = "hello";
17   while (state.KeepRunning())
18     std::string copy(x);
19 }
20 BENCHMARK(BM_StringCopy);
21 
22 // Augment the main() program to invoke benchmarks if specified
23 // via the --benchmarks command line flag.  E.g.,
24 //       my_unittest --benchmark_filter=all
25 //       my_unittest --benchmark_filter=BM_StringCreation
26 //       my_unittest --benchmark_filter=String
27 //       my_unittest --benchmark_filter='Copy|Creation'
28 int main(int argc, char** argv) {
29   benchmark::Initialize(&argc, argv);
30   benchmark::RunSpecifiedBenchmarks();
31   return 0;
32 }
33 
34 // Sometimes a family of microbenchmarks can be implemented with
35 // just one routine that takes an extra argument to specify which
36 // one of the family of benchmarks to run.  For example, the following
37 // code defines a family of microbenchmarks for measuring the speed
38 // of memcpy() calls of different lengths:
39 
40 static void BM_memcpy(benchmark::State& state) {
41   char* src = new char[state.range_x()]; char* dst = new char[state.range_x()];
42   memset(src, 'x', state.range_x());
43   while (state.KeepRunning())
44     memcpy(dst, src, state.range_x());
45   state.SetBytesProcessed(int64_t(state.iterations()) *
46                           int64_t(state.range_x()));
47   delete[] src; delete[] dst;
48 }
49 BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10);
50 
51 // The preceding code is quite repetitive, and can be replaced with the
52 // following short-hand.  The following invocation will pick a few
53 // appropriate arguments in the specified range and will generate a
54 // microbenchmark for each such argument.
55 BENCHMARK(BM_memcpy)->Range(8, 8<<10);
56 
57 // You might have a microbenchmark that depends on two inputs.  For
58 // example, the following code defines a family of microbenchmarks for
59 // measuring the speed of set insertion.
60 static void BM_SetInsert(benchmark::State& state) {
61   while (state.KeepRunning()) {
62     state.PauseTiming();
63     set<int> data = ConstructRandomSet(state.range_x());
64     state.ResumeTiming();
65     for (int j = 0; j < state.range_y(); ++j)
66       data.insert(RandomNumber());
67   }
68 }
69 BENCHMARK(BM_SetInsert)
70    ->ArgPair(1<<10, 1)
71    ->ArgPair(1<<10, 8)
72    ->ArgPair(1<<10, 64)
73    ->ArgPair(1<<10, 512)
74    ->ArgPair(8<<10, 1)
75    ->ArgPair(8<<10, 8)
76    ->ArgPair(8<<10, 64)
77    ->ArgPair(8<<10, 512);
78 
79 // The preceding code is quite repetitive, and can be replaced with
80 // the following short-hand.  The following macro will pick a few
81 // appropriate arguments in the product of the two specified ranges
82 // and will generate a microbenchmark for each such pair.
83 BENCHMARK(BM_SetInsert)->RangePair(1<<10, 8<<10, 1, 512);
84 
85 // For more complex patterns of inputs, passing a custom function
86 // to Apply allows programmatic specification of an
87 // arbitrary set of arguments to run the microbenchmark on.
88 // The following example enumerates a dense range on
89 // one parameter, and a sparse range on the second.
90 static void CustomArguments(benchmark::internal::Benchmark* b) {
91   for (int i = 0; i <= 10; ++i)
92     for (int j = 32; j <= 1024*1024; j *= 8)
93       b->ArgPair(i, j);
94 }
95 BENCHMARK(BM_SetInsert)->Apply(CustomArguments);
96 
97 // Templated microbenchmarks work the same way:
98 // Produce then consume 'size' messages 'iters' times
99 // Measures throughput in the absence of multiprogramming.
100 template <class Q> int BM_Sequential(benchmark::State& state) {
101   Q q;
102   typename Q::value_type v;
103   while (state.KeepRunning()) {
104     for (int i = state.range_x(); i--; )
105       q.push(v);
106     for (int e = state.range_x(); e--; )
107       q.Wait(&v);
108   }
109   // actually messages, not bytes:
110   state.SetBytesProcessed(
111       static_cast<int64_t>(state.iterations())*state.range_x());
112 }
113 BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue<int>)->Range(1<<0, 1<<10);
114 
115 Use `Benchmark::MinTime(double t)` to set the minimum time used to run the
116 benchmark. This option overrides the `benchmark_min_time` flag.
117 
118 void BM_test(benchmark::State& state) {
119  ... body ...
120 }
121 BENCHMARK(BM_test)->MinTime(2.0); // Run for at least 2 seconds.
122 
123 In a multithreaded test, it is guaranteed that none of the threads will start
124 until all have called KeepRunning, and all will have finished before KeepRunning
125 returns false. As such, any global setup or teardown you want to do can be
126 wrapped in a check against the thread index:
127 
128 static void BM_MultiThreaded(benchmark::State& state) {
129   if (state.thread_index == 0) {
130     // Setup code here.
131   }
132   while (state.KeepRunning()) {
133     // Run the test as normal.
134   }
135   if (state.thread_index == 0) {
136     // Teardown code here.
137   }
138 }
139 BENCHMARK(BM_MultiThreaded)->Threads(4);
140 */
141 
142 #ifndef BENCHMARK_BENCHMARK_API_H_
143 #define BENCHMARK_BENCHMARK_API_H_
144 
145 #include <assert.h>
146 #include <stddef.h>
147 #include <stdint.h>
148 
149 #include "macros.h"
150 
151 namespace benchmark {
152 class BenchmarkReporter;
153 
154 void Initialize(int* argc, char** argv);
155 
156 // Otherwise, run all benchmarks specified by the --benchmark_filter flag,
157 // and exit after running the benchmarks.
158 void RunSpecifiedBenchmarks();
159 void RunSpecifiedBenchmarks(BenchmarkReporter* reporter);
160 
161 // If this routine is called, peak memory allocation past this point in the
162 // benchmark is reported at the end of the benchmark report line. (It is
163 // computed by running the benchmark once with a single iteration and a memory
164 // tracer.)
165 // TODO(dominic)
166 // void MemoryUsage();
167 
168 namespace internal {
169 class Benchmark;
170 class BenchmarkImp;
171 class BenchmarkFamilies;
172 
173 template <class T> struct Voider {
174     typedef void type;
175 };
176 
177 template <class T, class = void>
178 struct EnableIfString {};
179 
180 template <class T>
181 struct EnableIfString<T, typename Voider<typename T::basic_string>::type> {
182     typedef int type;
183 };
184 
185 void UseCharPointer(char const volatile*);
186 
187 // Take ownership of the pointer and register the benchmark. Return the
188 // registered benchmark.
189 Benchmark* RegisterBenchmarkInternal(Benchmark*);
190 
191 } // end namespace internal
192 
193 
194 // The DoNotOptimize(...) function can be used to prevent a value or
195 // expression from being optimized away by the compiler. This function is
196 // intented to add little to no overhead.
197 // See: http://stackoverflow.com/questions/28287064
198 #if defined(__clang__) && defined(__GNUC__)
199 // TODO(ericwf): Clang has a bug where it tries to always use a register
200 // even if value must be stored in memory. This causes codegen to fail.
201 // To work around this we remove the "r" modifier so the operand is always
202 // loaded into memory.
203 template <class Tp>
204 inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) {
205     asm volatile("" : "+m" (const_cast<Tp&>(value)));
206 }
207 #elif defined(__GNUC__)
208 template <class Tp>
209 inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) {
210     asm volatile("" : "+rm" (const_cast<Tp&>(value)));
211 }
212 #else
213 template <class Tp>
214 inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) {
215     internal::UseCharPointer(&reinterpret_cast<char const volatile&>(value));
216 }
217 #endif
218 
219 
220 // State is passed to a running Benchmark and contains state for the
221 // benchmark to use.
222 class State {
223 public:
224   State(size_t max_iters, bool has_x, int x, bool has_y, int y, int thread_i, int n_threads);
225 
226   // Returns true iff the benchmark should continue through another iteration.
227   // NOTE: A benchmark may not return from the test until KeepRunning() has
228   // returned false.
229   bool KeepRunning() {
230     if (BENCHMARK_BUILTIN_EXPECT(!started_, false)) {
231         ResumeTiming();
232         started_ = true;
233     }
234     bool const res = total_iterations_++ < max_iterations;
235     if (BENCHMARK_BUILTIN_EXPECT(!res, false)) {
236         assert(started_);
237         PauseTiming();
238         // Total iterations now is one greater than max iterations. Fix this.
239         total_iterations_ = max_iterations;
240     }
241     return res;
242   }
243 
244   // REQUIRES: timer is running
245   // Stop the benchmark timer.  If not called, the timer will be
246   // automatically stopped after KeepRunning() returns false for the first time.
247   //
248   // For threaded benchmarks the PauseTiming() function acts
249   // like a barrier.  I.e., the ith call by a particular thread to this
250   // function will block until all threads have made their ith call.
251   // The timer will stop when the last thread has called this function.
252   //
253   // NOTE: PauseTiming()/ResumeTiming() are relatively
254   // heavyweight, and so their use should generally be avoided
255   // within each benchmark iteration, if possible.
256   void PauseTiming();
257 
258   // REQUIRES: timer is not running
259   // Start the benchmark timer.  The timer is NOT running on entrance to the
260   // benchmark function. It begins running after the first call to KeepRunning()
261   //
262   // For threaded benchmarks the ResumeTiming() function acts
263   // like a barrier.  I.e., the ith call by a particular thread to this
264   // function will block until all threads have made their ith call.
265   // The timer will start when the last thread has called this function.
266   //
267   // NOTE: PauseTiming()/ResumeTiming() are relatively
268   // heavyweight, and so their use should generally be avoided
269   // within each benchmark iteration, if possible.
270   void ResumeTiming();
271 
272   // Set the number of bytes processed by the current benchmark
273   // execution.  This routine is typically called once at the end of a
274   // throughput oriented benchmark.  If this routine is called with a
275   // value > 0, the report is printed in MB/sec instead of nanoseconds
276   // per iteration.
277   //
278   // REQUIRES: a benchmark has exited its KeepRunning loop.
279   BENCHMARK_ALWAYS_INLINE
280   void SetBytesProcessed(size_t bytes) {
281     bytes_processed_ = bytes;
282   }
283 
284   BENCHMARK_ALWAYS_INLINE
285   size_t bytes_processed() const {
286     return bytes_processed_;
287   }
288 
289   // If this routine is called with items > 0, then an items/s
290   // label is printed on the benchmark report line for the currently
291   // executing benchmark. It is typically called at the end of a processing
292   // benchmark where a processing items/second output is desired.
293   //
294   // REQUIRES: a benchmark has exited its KeepRunning loop.
295   BENCHMARK_ALWAYS_INLINE
296   void SetItemsProcessed(size_t items) {
297     items_processed_ = items;
298   }
299 
300   BENCHMARK_ALWAYS_INLINE
301   size_t items_processed() const {
302     return items_processed_;
303   }
304 
305   // If this routine is called, the specified label is printed at the
306   // end of the benchmark report line for the currently executing
307   // benchmark.  Example:
308   //  static void BM_Compress(int iters) {
309   //    ...
310   //    double compress = input_size / output_size;
311   //    benchmark::SetLabel(StringPrintf("compress:%.1f%%", 100.0*compression));
312   //  }
313   // Produces output that looks like:
314   //  BM_Compress   50         50   14115038  compress:27.3%
315   //
316   // REQUIRES: a benchmark has exited its KeepRunning loop.
317   void SetLabel(const char* label);
318 
319   // Allow the use of std::string without actually including <string>.
320   // This function does not participate in overload resolution unless StringType
321   // has the nested typename `basic_string`. This typename should be provided
322   // as an injected class name in the case of std::string.
323   template <class StringType>
324   void SetLabel(StringType const & str,
325                 typename internal::EnableIfString<StringType>::type = 1) {
326     this->SetLabel(str.c_str());
327   }
328 
329   // Range arguments for this run. CHECKs if the argument has been set.
330   BENCHMARK_ALWAYS_INLINE
331   int range_x() const {
332     assert(has_range_x_);
333     ((void)has_range_x_); // Prevent unused warning.
334     return range_x_;
335   }
336 
337   BENCHMARK_ALWAYS_INLINE
338   int range_y() const {
339     assert(has_range_y_);
340     ((void)has_range_y_); // Prevent unused warning.
341     return range_y_;
342   }
343 
344   BENCHMARK_ALWAYS_INLINE
345   size_t iterations() const { return total_iterations_; }
346 
347 private:
348   bool started_;
349   size_t total_iterations_;
350 
351   bool has_range_x_;
352   int range_x_;
353 
354   bool has_range_y_;
355   int range_y_;
356 
357   size_t bytes_processed_;
358   size_t items_processed_;
359 
360 public:
361   // Index of the executing thread. Values from [0, threads).
362   const int thread_index;
363   // Number of threads concurrently executing the benchmark.
364   const int threads;
365   const size_t max_iterations;
366 
367 private:
368   BENCHMARK_DISALLOW_COPY_AND_ASSIGN(State);
369 };
370 
371 namespace internal {
372 
373 typedef void(Function)(State&);
374 
375 // ------------------------------------------------------
376 // Benchmark registration object.  The BENCHMARK() macro expands
377 // into an internal::Benchmark* object.  Various methods can
378 // be called on this object to change the properties of the benchmark.
379 // Each method returns "this" so that multiple method calls can
380 // chained into one expression.
381 class Benchmark {
382 public:
383   virtual ~Benchmark();
384 
385   // Note: the following methods all return "this" so that multiple
386   // method calls can be chained together in one expression.
387 
388   // Run this benchmark once with "x" as the extra argument passed
389   // to the function.
390   // REQUIRES: The function passed to the constructor must accept an arg1.
391   Benchmark* Arg(int x);
392 
393   // Run this benchmark once for a number of values picked from the
394   // range [start..limit].  (start and limit are always picked.)
395   // REQUIRES: The function passed to the constructor must accept an arg1.
396   Benchmark* Range(int start, int limit);
397 
398   // Run this benchmark once for every value in the range [start..limit]
399   // REQUIRES: The function passed to the constructor must accept an arg1.
400   Benchmark* DenseRange(int start, int limit);
401 
402   // Run this benchmark once with "x,y" as the extra arguments passed
403   // to the function.
404   // REQUIRES: The function passed to the constructor must accept arg1,arg2.
405   Benchmark* ArgPair(int x, int y);
406 
407   // Pick a set of values A from the range [lo1..hi1] and a set
408   // of values B from the range [lo2..hi2].  Run the benchmark for
409   // every pair of values in the cartesian product of A and B
410   // (i.e., for all combinations of the values in A and B).
411   // REQUIRES: The function passed to the constructor must accept arg1,arg2.
412   Benchmark* RangePair(int lo1, int hi1, int lo2, int hi2);
413 
414   // Pass this benchmark object to *func, which can customize
415   // the benchmark by calling various methods like Arg, ArgPair,
416   // Threads, etc.
417   Benchmark* Apply(void (*func)(Benchmark* benchmark));
418 
419   // Set the minimum amount of time to use when running this benchmark. This
420   // option overrides the `benchmark_min_time` flag.
421   Benchmark* MinTime(double t);
422 
423   // If a particular benchmark is I/O bound, runs multiple threads internally or
424   // if for some reason CPU timings are not representative, call this method. If
425   // called, the elapsed time will be used to control how many iterations are
426   // run, and in the printing of items/second or MB/seconds values.  If not
427   // called, the cpu time used by the benchmark will be used.
428   Benchmark* UseRealTime();
429 
430   // Support for running multiple copies of the same benchmark concurrently
431   // in multiple threads.  This may be useful when measuring the scaling
432   // of some piece of code.
433 
434   // Run one instance of this benchmark concurrently in t threads.
435   Benchmark* Threads(int t);
436 
437   // Pick a set of values T from [min_threads,max_threads].
438   // min_threads and max_threads are always included in T.  Run this
439   // benchmark once for each value in T.  The benchmark run for a
440   // particular value t consists of t threads running the benchmark
441   // function concurrently.  For example, consider:
442   //    BENCHMARK(Foo)->ThreadRange(1,16);
443   // This will run the following benchmarks:
444   //    Foo in 1 thread
445   //    Foo in 2 threads
446   //    Foo in 4 threads
447   //    Foo in 8 threads
448   //    Foo in 16 threads
449   Benchmark* ThreadRange(int min_threads, int max_threads);
450 
451   // Equivalent to ThreadRange(NumCPUs(), NumCPUs())
452   Benchmark* ThreadPerCpu();
453 
454   virtual void Run(State& state) = 0;
455 
456   // Used inside the benchmark implementation
457   struct Instance;
458 
459 protected:
460   explicit Benchmark(const char* name);
461   Benchmark(Benchmark const&);
462   void SetName(const char* name);
463 
464 private:
465   friend class BenchmarkFamilies;
466   BenchmarkImp* imp_;
467 
468   Benchmark& operator=(Benchmark const&);
469 };
470 
471 // The class used to hold all Benchmarks created from static function.
472 // (ie those created using the BENCHMARK(...) macros.
473 class FunctionBenchmark : public Benchmark {
474 public:
475     FunctionBenchmark(const char* name, Function* func)
476         : Benchmark(name), func_(func)
477     {}
478 
479     virtual void Run(State& st);
480 private:
481     Function* func_;
482 };
483 
484 }  // end namespace internal
485 
486 // The base class for all fixture tests.
487 class Fixture: public internal::Benchmark {
488 public:
489     Fixture() : internal::Benchmark("") {}
490 
491     virtual void Run(State& st) {
492       this->SetUp(st);
493       this->BenchmarkCase(st);
494       this->TearDown();
495     }
496 
497     virtual void SetUp(const State&) {}
498     virtual void TearDown() {}
499 
500 protected:
501     virtual void BenchmarkCase(State&) = 0;
502 };
503 
504 }  // end namespace benchmark
505 
506 
507 // ------------------------------------------------------
508 // Macro to register benchmarks
509 
510 // Check that __COUNTER__ is defined and that __COUNTER__ increases by 1
511 // every time it is expanded. X + 1 == X + 0 is used in case X is defined to be
512 // empty. If X is empty the expression becomes (+1 == +0).
513 #if defined(__COUNTER__) && (__COUNTER__ + 1 == __COUNTER__ + 0)
514 #define BENCHMARK_PRIVATE_UNIQUE_ID __COUNTER__
515 #else
516 #define BENCHMARK_PRIVATE_UNIQUE_ID __LINE__
517 #endif
518 
519 // Helpers for generating unique variable names
520 #define BENCHMARK_PRIVATE_NAME(n) \
521     BENCHMARK_PRIVATE_CONCAT(_benchmark_, BENCHMARK_PRIVATE_UNIQUE_ID, n)
522 #define BENCHMARK_PRIVATE_CONCAT(a, b, c) BENCHMARK_PRIVATE_CONCAT2(a, b, c)
523 #define BENCHMARK_PRIVATE_CONCAT2(a, b, c) a##b##c
524 
525 #define BENCHMARK_PRIVATE_DECLARE(n)       \
526   static ::benchmark::internal::Benchmark* \
527   BENCHMARK_PRIVATE_NAME(n) BENCHMARK_UNUSED
528 
529 #define BENCHMARK(n) \
530     BENCHMARK_PRIVATE_DECLARE(n) =                               \
531         (::benchmark::internal::RegisterBenchmarkInternal(       \
532             new ::benchmark::internal::FunctionBenchmark(#n, n)))
533 
534 // Old-style macros
535 #define BENCHMARK_WITH_ARG(n, a) BENCHMARK(n)->Arg((a))
536 #define BENCHMARK_WITH_ARG2(n, a1, a2) BENCHMARK(n)->ArgPair((a1), (a2))
537 #define BENCHMARK_RANGE(n, lo, hi) BENCHMARK(n)->Range((lo), (hi))
538 #define BENCHMARK_RANGE2(n, l1, h1, l2, h2) \
539   BENCHMARK(n)->RangePair((l1), (h1), (l2), (h2))
540 
541 // This will register a benchmark for a templatized function.  For example:
542 //
543 // template<int arg>
544 // void BM_Foo(int iters);
545 //
546 // BENCHMARK_TEMPLATE(BM_Foo, 1);
547 //
548 // will register BM_Foo<1> as a benchmark.
549 #define BENCHMARK_TEMPLATE1(n, a) \
550   BENCHMARK_PRIVATE_DECLARE(n) =  \
551       (::benchmark::internal::RegisterBenchmarkInternal( \
552         new ::benchmark::internal::FunctionBenchmark(#n "<" #a ">", n<a>)))
553 
554 #define BENCHMARK_TEMPLATE2(n, a, b)                     \
555   BENCHMARK_PRIVATE_DECLARE(n) =                         \
556       (::benchmark::internal::RegisterBenchmarkInternal( \
557         new ::benchmark::internal::FunctionBenchmark(    \
558             #n "<" #a "," #b ">", n<a, b>)))
559 
560 #if __cplusplus >= 201103L
561 #define BENCHMARK_TEMPLATE(n, ...)           \
562   BENCHMARK_PRIVATE_DECLARE(n) =             \
563       (::benchmark::internal::RegisterBenchmarkInternal( \
564         new ::benchmark::internal::FunctionBenchmark( \
565         #n "<" #__VA_ARGS__ ">", n<__VA_ARGS__>)))
566 #else
567 #define BENCHMARK_TEMPLATE(n, a) BENCHMARK_TEMPLATE1(n, a)
568 #endif
569 
570 
571 #define BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method)      \
572 class BaseClass##_##Method##_Benchmark : public BaseClass { \
573 public:                                                     \
574     BaseClass##_##Method##_Benchmark() : BaseClass() {      \
575         this->SetName(#BaseClass "/" #Method);}             \
576 protected:                                                  \
577     virtual void BenchmarkCase(::benchmark::State&);        \
578 };
579 
580 #define BENCHMARK_DEFINE_F(BaseClass, Method) \
581     BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \
582     void BaseClass##_##Method##_Benchmark::BenchmarkCase
583 
584 #define BENCHMARK_REGISTER_F(BaseClass, Method) \
585     BENCHMARK_PRIVATE_REGISTER_F(BaseClass##_##Method##_Benchmark)
586 
587 #define BENCHMARK_PRIVATE_REGISTER_F(TestName) \
588     BENCHMARK_PRIVATE_DECLARE(TestName) = \
589         (::benchmark::internal::RegisterBenchmarkInternal(new TestName()))
590 
591 // This macro will define and register a benchmark within a fixture class.
592 #define BENCHMARK_F(BaseClass, Method) \
593     BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \
594     BENCHMARK_REGISTER_F(BaseClass, Method); \
595     void BaseClass##_##Method##_Benchmark::BenchmarkCase
596 
597 
598 // Helper macro to create a main routine in a test that runs the benchmarks
599 #define BENCHMARK_MAIN()                   \
600   int main(int argc, char** argv) {        \
601     ::benchmark::Initialize(&argc, argv);  \
602     ::benchmark::RunSpecifiedBenchmarks(); \
603   }
604 
605 #endif  // BENCHMARK_BENCHMARK_API_H_
606