1 // Support for registering benchmarks for functions.
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;
11 // Register the function as a benchmark
12 BENCHMARK(BM_StringCreation);
14 // Define another benchmark
15 static void BM_StringCopy(benchmark::State& state) {
16 std::string x = "hello";
17 while (state.KeepRunning())
20 BENCHMARK(BM_StringCopy);
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();
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:
40 static void BM_memcpy(benchmark::State& state) {
41 char* src = new char[state.range(0)]; char* dst = new char[state.range(0)];
42 memset(src, 'x', state.range(0));
43 while (state.KeepRunning())
44 memcpy(dst, src, state.range(0));
45 state.SetBytesProcessed(int64_t(state.iterations()) *
46 int64_t(state.range(0)));
47 delete[] src; delete[] dst;
49 BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10);
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);
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()) {
63 set<int> data = ConstructRandomSet(state.range(0));
65 for (int j = 0; j < state.range(1); ++j)
66 data.insert(RandomNumber());
69 BENCHMARK(BM_SetInsert)
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)->Ranges({{1<<10, 8<<10}, {1, 512}});
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)
95 BENCHMARK(BM_SetInsert)->Apply(CustomArguments);
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) {
102 typename Q::value_type v;
103 while (state.KeepRunning()) {
104 for (int i = state.range(0); i--; )
106 for (int e = state.range(0); e--; )
109 // actually messages, not bytes:
110 state.SetBytesProcessed(
111 static_cast<int64_t>(state.iterations())*state.range(0));
113 BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue<int>)->Range(1<<0, 1<<10);
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.
118 void BM_test(benchmark::State& state) {
121 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 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:
128 static void BM_MultiThreaded(benchmark::State& state) {
129 if (state.thread_index == 0) {
132 while (state.KeepRunning()) {
133 // Run the test as normal.
135 if (state.thread_index == 0) {
136 // Teardown code here.
139 BENCHMARK(BM_MultiThreaded)->Threads(4);
142 If a benchmark runs a few milliseconds it may be hard to visually compare the
143 measured times, since the output data is given in nanoseconds per default. In
144 order to manually set the time unit, you can specify it manually:
146 BENCHMARK(BM_test)->Unit(benchmark::kMillisecond);
149 #ifndef BENCHMARK_BENCHMARK_API_H_
150 #define BENCHMARK_BENCHMARK_API_H_
161 #if defined(BENCHMARK_HAS_CXX11)
162 #include <type_traits>
166 namespace benchmark {
167 class BenchmarkReporter;
169 void Initialize(int* argc, char** argv);
171 // Generate a list of benchmarks matching the specified --benchmark_filter flag
172 // and if --benchmark_list_tests is specified return after printing the name
173 // of each matching benchmark. Otherwise run each matching benchmark and
174 // report the results.
176 // The second and third overload use the specified 'console_reporter' and
177 // 'file_reporter' respectively. 'file_reporter' will write to the file
179 // by '--benchmark_output'. If '--benchmark_output' is not given the
180 // 'file_reporter' is ignored.
182 // RETURNS: The number of matching benchmarks.
183 size_t RunSpecifiedBenchmarks();
184 size_t RunSpecifiedBenchmarks(BenchmarkReporter* console_reporter);
185 size_t RunSpecifiedBenchmarks(BenchmarkReporter* console_reporter,
186 BenchmarkReporter* file_reporter);
188 // If this routine is called, peak memory allocation past this point in the
189 // benchmark is reported at the end of the benchmark report line. (It is
190 // computed by running the benchmark once with a single iteration and a memory
193 // void MemoryUsage();
198 class BenchmarkFamilies;
205 template <class T, class = void>
206 struct EnableIfString {};
209 struct EnableIfString<T, typename Voider<typename T::basic_string>::type> {
213 void UseCharPointer(char const volatile*);
215 // Take ownership of the pointer and register the benchmark. Return the
216 // registered benchmark.
217 Benchmark* RegisterBenchmarkInternal(Benchmark*);
219 // Ensure that the standard streams are properly initialized in every TU.
220 int InitializeStreams();
221 BENCHMARK_UNUSED static int stream_init_anchor = InitializeStreams();
223 } // end namespace internal
225 // The DoNotOptimize(...) function can be used to prevent a value or
226 // expression from being optimized away by the compiler. This function is
227 // intended to add little to no overhead.
228 // See: https://youtu.be/nXaxk27zwlk?t=2441
229 #if defined(__GNUC__)
231 inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) {
232 asm volatile("" : : "g"(value) : "memory");
234 // Force the compiler to flush pending writes to global memory. Acts as an
235 // effective read/write barrier
236 inline BENCHMARK_ALWAYS_INLINE void ClobberMemory() {
237 asm volatile("" : : : "memory");
241 inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) {
242 internal::UseCharPointer(&reinterpret_cast<char const volatile&>(value));
244 // FIXME Add ClobberMemory() for non-gnu compilers
247 // TimeUnit is passed to a benchmark in order to specify the order of magnitude
248 // for the measured time.
249 enum TimeUnit { kNanosecond, kMicrosecond, kMillisecond };
251 // BigO is passed to a benchmark in order to specify the asymptotic
253 // complexity for the benchmark. In case oAuto is selected, complexity will be
254 // calculated automatically to the best fit.
255 enum BigO { oNone, o1, oN, oNSquared, oNCubed, oLogN, oNLogN, oAuto, oLambda };
257 // BigOFunc is passed to a benchmark in order to specify the asymptotic
258 // computational complexity for the benchmark.
259 typedef double(BigOFunc)(int);
265 #if defined(BENCHMARK_HAS_CXX11)
266 enum ReportMode : unsigned {
270 RM_Unspecified, // The mode has not been manually specified
271 RM_Default, // The mode is user-specified as default.
272 RM_ReportAggregatesOnly
276 // State is passed to a running Benchmark and contains state for the
280 // Returns true if the benchmark should continue through another iteration.
281 // NOTE: A benchmark may not return from the test until KeepRunning() has
284 if (BENCHMARK_BUILTIN_EXPECT(!started_, false)) {
287 bool const res = total_iterations_++ < max_iterations;
288 if (BENCHMARK_BUILTIN_EXPECT(!res, false)) {
294 // REQUIRES: timer is running and 'SkipWithError(...)' has not been called
295 // by the current thread.
296 // Stop the benchmark timer. If not called, the timer will be
297 // automatically stopped after KeepRunning() returns false for the first time.
299 // For threaded benchmarks the PauseTiming() function only pauses the timing
300 // for the current thread.
302 // NOTE: The "real time" measurement is per-thread. If different threads
303 // report different measurements the largest one is reported.
305 // NOTE: PauseTiming()/ResumeTiming() are relatively
306 // heavyweight, and so their use should generally be avoided
307 // within each benchmark iteration, if possible.
310 // REQUIRES: timer is not running and 'SkipWithError(...)' has not been called
311 // by the current thread.
312 // Start the benchmark timer. The timer is NOT running on entrance to the
313 // benchmark function. It begins running after the first call to KeepRunning()
315 // NOTE: PauseTiming()/ResumeTiming() are relatively
316 // heavyweight, and so their use should generally be avoided
317 // within each benchmark iteration, if possible.
320 // REQUIRES: 'SkipWithError(...)' has not been called previously by the
322 // Skip any future iterations of the 'KeepRunning()' loop in the current
323 // thread and report an error with the specified 'msg'. After this call
324 // the user may explicitly 'return' from the benchmark.
326 // For threaded benchmarks only the current thread stops executing and future
327 // calls to `KeepRunning()` will block until all threads have completed
328 // the `KeepRunning()` loop. If multiple threads report an error only the
329 // first error message is used.
331 // NOTE: Calling 'SkipWithError(...)' does not cause the benchmark to exit
332 // the current scope immediately. If the function is called from within
333 // the 'KeepRunning()' loop the current iteration will finish. It is the users
334 // responsibility to exit the scope as needed.
335 void SkipWithError(const char* msg);
337 // REQUIRES: called exactly once per iteration of the KeepRunning loop.
338 // Set the manually measured time for this benchmark iteration, which
339 // is used instead of automatically measured time if UseManualTime() was
342 // For threaded benchmarks the final value will be set to the largest
344 void SetIterationTime(double seconds);
346 // Set the number of bytes processed by the current benchmark
347 // execution. This routine is typically called once at the end of a
348 // throughput oriented benchmark. If this routine is called with a
349 // value > 0, the report is printed in MB/sec instead of nanoseconds
352 // REQUIRES: a benchmark has exited its KeepRunning loop.
353 BENCHMARK_ALWAYS_INLINE
354 void SetBytesProcessed(size_t bytes) { bytes_processed_ = bytes; }
356 BENCHMARK_ALWAYS_INLINE
357 size_t bytes_processed() const { return bytes_processed_; }
359 // If this routine is called with complexity_n > 0 and complexity report is
361 // family benchmark, then current benchmark will be part of the computation
362 // and complexity_n will
363 // represent the length of N.
364 BENCHMARK_ALWAYS_INLINE
365 void SetComplexityN(int complexity_n) { complexity_n_ = complexity_n; }
367 BENCHMARK_ALWAYS_INLINE
368 int complexity_length_n() { return complexity_n_; }
370 // If this routine is called with items > 0, then an items/s
371 // label is printed on the benchmark report line for the currently
372 // executing benchmark. It is typically called at the end of a processing
373 // benchmark where a processing items/second output is desired.
375 // REQUIRES: a benchmark has exited its KeepRunning loop.
376 BENCHMARK_ALWAYS_INLINE
377 void SetItemsProcessed(size_t items) { items_processed_ = items; }
379 BENCHMARK_ALWAYS_INLINE
380 size_t items_processed() const { return items_processed_; }
382 // If this routine is called, the specified label is printed at the
383 // end of the benchmark report line for the currently executing
384 // benchmark. Example:
385 // static void BM_Compress(benchmark::State& state) {
387 // double compress = input_size / output_size;
388 // state.SetLabel(StringPrintf("compress:%.1f%%", 100.0*compression));
390 // Produces output that looks like:
391 // BM_Compress 50 50 14115038 compress:27.3%
393 // REQUIRES: a benchmark has exited its KeepRunning loop.
394 void SetLabel(const char* label);
396 // Allow the use of std::string without actually including <string>.
397 // This function does not participate in overload resolution unless StringType
398 // has the nested typename `basic_string`. This typename should be provided
399 // as an injected class name in the case of std::string.
400 template <class StringType>
401 void SetLabel(StringType const& str,
402 typename internal::EnableIfString<StringType>::type = 1) {
403 this->SetLabel(str.c_str());
406 // Range arguments for this run. CHECKs if the argument has been set.
407 BENCHMARK_ALWAYS_INLINE
408 int range(std::size_t pos = 0) const {
409 assert(range_.size() > pos);
413 BENCHMARK_DEPRECATED_MSG("use 'range(0)' instead")
414 int range_x() const { return range(0); }
416 BENCHMARK_DEPRECATED_MSG("use 'range(1)' instead")
417 int range_y() const { return range(1); }
419 BENCHMARK_ALWAYS_INLINE
420 size_t iterations() const { return total_iterations_; }
425 size_t total_iterations_;
427 std::vector<int> range_;
429 size_t bytes_processed_;
430 size_t items_processed_;
434 bool error_occurred_;
437 // Index of the executing thread. Values from [0, threads).
438 const int thread_index;
439 // Number of threads concurrently executing the benchmark.
441 const size_t max_iterations;
443 // TODO make me private
444 State(size_t max_iters, const std::vector<int>& ranges, int thread_i,
445 int n_threads, internal::ThreadTimer* timer,
446 internal::ThreadManager* manager);
449 void StartKeepRunning();
450 void FinishKeepRunning();
451 internal::ThreadTimer* timer_;
452 internal::ThreadManager* manager_;
453 BENCHMARK_DISALLOW_COPY_AND_ASSIGN(State);
458 typedef void(Function)(State&);
460 // ------------------------------------------------------
461 // Benchmark registration object. The BENCHMARK() macro expands
462 // into an internal::Benchmark* object. Various methods can
463 // be called on this object to change the properties of the benchmark.
464 // Each method returns "this" so that multiple method calls can
465 // chained into one expression.
468 virtual ~Benchmark();
470 // Note: the following methods all return "this" so that multiple
471 // method calls can be chained together in one expression.
473 // Run this benchmark once with "x" as the extra argument passed
475 // REQUIRES: The function passed to the constructor must accept an arg1.
476 Benchmark* Arg(int x);
478 // Run this benchmark with the given time unit for the generated output report
479 Benchmark* Unit(TimeUnit unit);
481 // Run this benchmark once for a number of values picked from the
482 // range [start..limit]. (start and limit are always picked.)
483 // REQUIRES: The function passed to the constructor must accept an arg1.
484 Benchmark* Range(int start, int limit);
486 // Run this benchmark once for all values in the range [start..limit] with
488 // REQUIRES: The function passed to the constructor must accept an arg1.
489 Benchmark* DenseRange(int start, int limit, int step = 1);
491 // Run this benchmark once with "args" as the extra arguments passed
493 // REQUIRES: The function passed to the constructor must accept arg1, arg2 ...
494 Benchmark* Args(const std::vector<int>& args);
496 // Equivalent to Args({x, y})
497 // NOTE: This is a legacy C++03 interface provided for compatibility only.
498 // New code should use 'Args'.
499 Benchmark* ArgPair(int x, int y) {
500 std::vector<int> args;
506 // Run this benchmark once for a number of values picked from the
507 // ranges [start..limit]. (starts and limits are always picked.)
508 // REQUIRES: The function passed to the constructor must accept arg1, arg2 ...
509 Benchmark* Ranges(const std::vector<std::pair<int, int> >& ranges);
511 // Equivalent to ArgNames({name})
512 Benchmark* ArgName(const std::string& name);
514 // Set the argument names to display in the benchmark name. If not called,
515 // only argument values will be shown.
516 Benchmark* ArgNames(const std::vector<std::string>& names);
518 // Equivalent to Ranges({{lo1, hi1}, {lo2, hi2}}).
519 // NOTE: This is a legacy C++03 interface provided for compatibility only.
520 // New code should use 'Ranges'.
521 Benchmark* RangePair(int lo1, int hi1, int lo2, int hi2) {
522 std::vector<std::pair<int, int> > ranges;
523 ranges.push_back(std::make_pair(lo1, hi1));
524 ranges.push_back(std::make_pair(lo2, hi2));
525 return Ranges(ranges);
528 // Pass this benchmark object to *func, which can customize
529 // the benchmark by calling various methods like Arg, Args,
531 Benchmark* Apply(void (*func)(Benchmark* benchmark));
533 // Set the range multiplier for non-dense range. If not called, the range
534 // multiplier kRangeMultiplier will be used.
535 Benchmark* RangeMultiplier(int multiplier);
537 // Set the minimum amount of time to use when running this benchmark. This
538 // option overrides the `benchmark_min_time` flag.
540 Benchmark* MinTime(double t);
542 // Specify the amount of times to repeat this benchmark. This option overrides
543 // the `benchmark_repetitions` flag.
545 Benchmark* Repetitions(int n);
547 // Specify if each repetition of the benchmark should be reported separately
548 // or if only the final statistics should be reported. If the benchmark
549 // is not repeated then the single result is always reported.
550 Benchmark* ReportAggregatesOnly(bool v = true);
552 // If a particular benchmark is I/O bound, runs multiple threads internally or
553 // if for some reason CPU timings are not representative, call this method. If
554 // called, the elapsed time will be used to control how many iterations are
555 // run, and in the printing of items/second or MB/seconds values. If not
556 // called, the cpu time used by the benchmark will be used.
557 Benchmark* UseRealTime();
559 // If a benchmark must measure time manually (e.g. if GPU execution time is
561 // measured), call this method. If called, each benchmark iteration should
563 // SetIterationTime(seconds) to report the measured time, which will be used
564 // to control how many iterations are run, and in the printing of items/second
565 // or MB/second values.
566 Benchmark* UseManualTime();
568 // Set the asymptotic computational complexity for the benchmark. If called
569 // the asymptotic computational complexity will be shown on the output.
570 Benchmark* Complexity(BigO complexity = benchmark::oAuto);
572 // Set the asymptotic computational complexity for the benchmark. If called
573 // the asymptotic computational complexity will be shown on the output.
574 Benchmark* Complexity(BigOFunc* complexity);
576 // Support for running multiple copies of the same benchmark concurrently
577 // in multiple threads. This may be useful when measuring the scaling
578 // of some piece of code.
580 // Run one instance of this benchmark concurrently in t threads.
581 Benchmark* Threads(int t);
583 // Pick a set of values T from [min_threads,max_threads].
584 // min_threads and max_threads are always included in T. Run this
585 // benchmark once for each value in T. The benchmark run for a
586 // particular value t consists of t threads running the benchmark
587 // function concurrently. For example, consider:
588 // BENCHMARK(Foo)->ThreadRange(1,16);
589 // This will run the following benchmarks:
595 Benchmark* ThreadRange(int min_threads, int max_threads);
597 // For each value n in the range, run this benchmark once using n threads.
598 // min_threads and max_threads are always included in the range.
599 // stride specifies the increment. E.g. DenseThreadRange(1, 8, 3) starts
600 // a benchmark with 1, 4, 7 and 8 threads.
601 Benchmark* DenseThreadRange(int min_threads, int max_threads, int stride = 1);
603 // Equivalent to ThreadRange(NumCPUs(), NumCPUs())
604 Benchmark* ThreadPerCpu();
606 virtual void Run(State& state) = 0;
608 // Used inside the benchmark implementation
612 explicit Benchmark(const char* name);
613 Benchmark(Benchmark const&);
614 void SetName(const char* name);
618 static void AddRange(std::vector<int>* dst, int lo, int hi, int mult);
621 friend class BenchmarkFamilies;
624 ReportMode report_mode_;
625 std::vector<std::string> arg_names_; // Args for all benchmark runs
626 std::vector<std::vector<int> > args_; // Args for all benchmark runs
628 int range_multiplier_;
632 bool use_manual_time_;
634 BigOFunc* complexity_lambda_;
635 std::vector<int> thread_counts_;
637 Benchmark& operator=(Benchmark const&);
640 } // namespace internal
642 // Create and register a benchmark with the specified 'name' that invokes
643 // the specified functor 'fn'.
645 // RETURNS: A pointer to the registered benchmark.
646 internal::Benchmark* RegisterBenchmark(const char* name,
647 internal::Function* fn);
649 #if defined(BENCHMARK_HAS_CXX11)
650 template <class Lambda>
651 internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn);
655 // The class used to hold all Benchmarks created from static function.
656 // (ie those created using the BENCHMARK(...) macros.
657 class FunctionBenchmark : public Benchmark {
659 FunctionBenchmark(const char* name, Function* func)
660 : Benchmark(name), func_(func) {}
662 virtual void Run(State& st);
668 #ifdef BENCHMARK_HAS_CXX11
669 template <class Lambda>
670 class LambdaBenchmark : public Benchmark {
672 virtual void Run(State& st) { lambda_(st); }
675 template <class OLambda>
676 LambdaBenchmark(const char* name, OLambda&& lam)
677 : Benchmark(name), lambda_(std::forward<OLambda>(lam)) {}
679 LambdaBenchmark(LambdaBenchmark const&) = delete;
683 friend Benchmark* ::benchmark::RegisterBenchmark(const char*, Lam&&);
689 } // end namespace internal
691 inline internal::Benchmark* RegisterBenchmark(const char* name,
692 internal::Function* fn) {
693 return internal::RegisterBenchmarkInternal(
694 ::new internal::FunctionBenchmark(name, fn));
697 #ifdef BENCHMARK_HAS_CXX11
698 template <class Lambda>
699 internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn) {
701 internal::LambdaBenchmark<typename std::decay<Lambda>::type>;
702 return internal::RegisterBenchmarkInternal(
703 ::new BenchType(name, std::forward<Lambda>(fn)));
707 #if defined(BENCHMARK_HAS_CXX11) && \
708 (!defined(BENCHMARK_GCC_VERSION) || BENCHMARK_GCC_VERSION >= 409)
709 template <class Lambda, class... Args>
710 internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn,
712 return benchmark::RegisterBenchmark(
713 name, [=](benchmark::State& st) { fn(st, args...); });
716 #define BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK
719 // The base class for all fixture tests.
720 class Fixture : public internal::Benchmark {
722 Fixture() : internal::Benchmark("") {}
724 virtual void Run(State& st) {
726 this->BenchmarkCase(st);
730 // These will be deprecated ...
731 virtual void SetUp(const State&) {}
732 virtual void TearDown(const State&) {}
733 // ... In favor of these.
734 virtual void SetUp(State& st) { SetUp(const_cast<const State&>(st)); }
735 virtual void TearDown(State& st) { TearDown(const_cast<const State&>(st)); }
738 virtual void BenchmarkCase(State&) = 0;
741 } // end namespace benchmark
743 // ------------------------------------------------------
744 // Macro to register benchmarks
746 // Check that __COUNTER__ is defined and that __COUNTER__ increases by 1
747 // every time it is expanded. X + 1 == X + 0 is used in case X is defined to be
748 // empty. If X is empty the expression becomes (+1 == +0).
749 #if defined(__COUNTER__) && (__COUNTER__ + 1 == __COUNTER__ + 0)
750 #define BENCHMARK_PRIVATE_UNIQUE_ID __COUNTER__
752 #define BENCHMARK_PRIVATE_UNIQUE_ID __LINE__
755 // Helpers for generating unique variable names
756 #define BENCHMARK_PRIVATE_NAME(n) \
757 BENCHMARK_PRIVATE_CONCAT(_benchmark_, BENCHMARK_PRIVATE_UNIQUE_ID, n)
758 #define BENCHMARK_PRIVATE_CONCAT(a, b, c) BENCHMARK_PRIVATE_CONCAT2(a, b, c)
759 #define BENCHMARK_PRIVATE_CONCAT2(a, b, c) a##b##c
761 #define BENCHMARK_PRIVATE_DECLARE(n) \
762 static ::benchmark::internal::Benchmark* BENCHMARK_PRIVATE_NAME(n) \
765 #define BENCHMARK(n) \
766 BENCHMARK_PRIVATE_DECLARE(n) = \
767 (::benchmark::internal::RegisterBenchmarkInternal( \
768 new ::benchmark::internal::FunctionBenchmark(#n, n)))
771 #define BENCHMARK_WITH_ARG(n, a) BENCHMARK(n)->Arg((a))
772 #define BENCHMARK_WITH_ARG2(n, a1, a2) BENCHMARK(n)->Args({(a1), (a2)})
773 #define BENCHMARK_WITH_UNIT(n, t) BENCHMARK(n)->Unit((t))
774 #define BENCHMARK_RANGE(n, lo, hi) BENCHMARK(n)->Range((lo), (hi))
775 #define BENCHMARK_RANGE2(n, l1, h1, l2, h2) \
776 BENCHMARK(n)->RangePair({{(l1), (h1)}, {(l2), (h2)}})
778 #if __cplusplus >= 201103L
780 // Register a benchmark which invokes the function specified by `func`
781 // with the additional arguments specified by `...`.
785 // template <class ...ExtraArgs>`
786 // void BM_takes_args(benchmark::State& state, ExtraArgs&&... extra_args) {
789 // /* Registers a benchmark named "BM_takes_args/int_string_test` */
790 // BENCHMARK_CAPTURE(BM_takes_args, int_string_test, 42, std::string("abc"));
791 #define BENCHMARK_CAPTURE(func, test_case_name, ...) \
792 BENCHMARK_PRIVATE_DECLARE(func) = \
793 (::benchmark::internal::RegisterBenchmarkInternal( \
794 new ::benchmark::internal::FunctionBenchmark( \
795 #func "/" #test_case_name, \
796 [](::benchmark::State& st) { func(st, __VA_ARGS__); })))
798 #endif // __cplusplus >= 11
800 // This will register a benchmark for a templatized function. For example:
803 // void BM_Foo(int iters);
805 // BENCHMARK_TEMPLATE(BM_Foo, 1);
807 // will register BM_Foo<1> as a benchmark.
808 #define BENCHMARK_TEMPLATE1(n, a) \
809 BENCHMARK_PRIVATE_DECLARE(n) = \
810 (::benchmark::internal::RegisterBenchmarkInternal( \
811 new ::benchmark::internal::FunctionBenchmark(#n "<" #a ">", n<a>)))
813 #define BENCHMARK_TEMPLATE2(n, a, b) \
814 BENCHMARK_PRIVATE_DECLARE(n) = \
815 (::benchmark::internal::RegisterBenchmarkInternal( \
816 new ::benchmark::internal::FunctionBenchmark(#n "<" #a "," #b ">", \
819 #if __cplusplus >= 201103L
820 #define BENCHMARK_TEMPLATE(n, ...) \
821 BENCHMARK_PRIVATE_DECLARE(n) = \
822 (::benchmark::internal::RegisterBenchmarkInternal( \
823 new ::benchmark::internal::FunctionBenchmark( \
824 #n "<" #__VA_ARGS__ ">", n<__VA_ARGS__>)))
826 #define BENCHMARK_TEMPLATE(n, a) BENCHMARK_TEMPLATE1(n, a)
829 #define BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \
830 class BaseClass##_##Method##_Benchmark : public BaseClass { \
832 BaseClass##_##Method##_Benchmark() : BaseClass() { \
833 this->SetName(#BaseClass "/" #Method); \
837 virtual void BenchmarkCase(::benchmark::State&); \
840 #define BENCHMARK_DEFINE_F(BaseClass, Method) \
841 BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \
842 void BaseClass##_##Method##_Benchmark::BenchmarkCase
844 #define BENCHMARK_REGISTER_F(BaseClass, Method) \
845 BENCHMARK_PRIVATE_REGISTER_F(BaseClass##_##Method##_Benchmark)
847 #define BENCHMARK_PRIVATE_REGISTER_F(TestName) \
848 BENCHMARK_PRIVATE_DECLARE(TestName) = \
849 (::benchmark::internal::RegisterBenchmarkInternal(new TestName()))
851 // This macro will define and register a benchmark within a fixture class.
852 #define BENCHMARK_F(BaseClass, Method) \
853 BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \
854 BENCHMARK_REGISTER_F(BaseClass, Method); \
855 void BaseClass##_##Method##_Benchmark::BenchmarkCase
857 // Helper macro to create a main routine in a test that runs the benchmarks
858 #define BENCHMARK_MAIN() \
859 int main(int argc, char** argv) { \
860 ::benchmark::Initialize(&argc, argv); \
861 ::benchmark::RunSpecifiedBenchmarks(); \
864 #endif // BENCHMARK_BENCHMARK_API_H_