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 
15 #include "benchmark_register.h"
16 
17 #ifndef BENCHMARK_OS_WINDOWS
18 #ifndef BENCHMARK_OS_FUCHSIA
19 #include <sys/resource.h>
20 #endif
21 #include <sys/time.h>
22 #include <unistd.h>
23 #endif
24 
25 #include <algorithm>
26 #include <atomic>
27 #include <cinttypes>
28 #include <condition_variable>
29 #include <cstdio>
30 #include <cstdlib>
31 #include <cstring>
32 #include <fstream>
33 #include <iostream>
34 #include <memory>
35 #include <numeric>
36 #include <sstream>
37 #include <thread>
38 
39 #include "benchmark/benchmark.h"
40 #include "benchmark_api_internal.h"
41 #include "check.h"
42 #include "commandlineflags.h"
43 #include "complexity.h"
44 #include "internal_macros.h"
45 #include "log.h"
46 #include "mutex.h"
47 #include "re.h"
48 #include "statistics.h"
49 #include "string_util.h"
50 #include "timers.h"
51 
52 namespace benchmark {
53 
54 namespace {
55 // For non-dense Range, intermediate values are powers of kRangeMultiplier.
56 static const int kRangeMultiplier = 8;
57 // The size of a benchmark family determines is the number of inputs to repeat
58 // the benchmark on. If this is "large" then warn the user during configuration.
59 static const size_t kMaxFamilySize = 100;
60 }  // end namespace
61 
62 namespace internal {
63 
64 //=============================================================================//
65 //                         BenchmarkFamilies
66 //=============================================================================//
67 
68 // Class for managing registered benchmarks.  Note that each registered
69 // benchmark identifies a family of related benchmarks to run.
70 class BenchmarkFamilies {
71  public:
72   static BenchmarkFamilies* GetInstance();
73 
74   // Registers a benchmark family and returns the index assigned to it.
75   size_t AddBenchmark(std::unique_ptr<Benchmark> family);
76 
77   // Clear all registered benchmark families.
78   void ClearBenchmarks();
79 
80   // Extract the list of benchmark instances that match the specified
81   // regular expression.
82   bool FindBenchmarks(std::string re,
83                       std::vector<BenchmarkInstance>* benchmarks,
84                       std::ostream* Err);
85 
86  private:
BenchmarkFamilies()87   BenchmarkFamilies() {}
88 
89   std::vector<std::unique_ptr<Benchmark>> families_;
90   Mutex mutex_;
91 };
92 
GetInstance()93 BenchmarkFamilies* BenchmarkFamilies::GetInstance() {
94   static BenchmarkFamilies instance;
95   return &instance;
96 }
97 
AddBenchmark(std::unique_ptr<Benchmark> family)98 size_t BenchmarkFamilies::AddBenchmark(std::unique_ptr<Benchmark> family) {
99   MutexLock l(mutex_);
100   size_t index = families_.size();
101   families_.push_back(std::move(family));
102   return index;
103 }
104 
ClearBenchmarks()105 void BenchmarkFamilies::ClearBenchmarks() {
106   MutexLock l(mutex_);
107   families_.clear();
108   families_.shrink_to_fit();
109 }
110 
FindBenchmarks(std::string spec,std::vector<BenchmarkInstance> * benchmarks,std::ostream * ErrStream)111 bool BenchmarkFamilies::FindBenchmarks(
112     std::string spec, std::vector<BenchmarkInstance>* benchmarks,
113     std::ostream* ErrStream) {
114   BM_CHECK(ErrStream);
115   auto& Err = *ErrStream;
116   // Make regular expression out of command-line flag
117   std::string error_msg;
118   Regex re;
119   bool isNegativeFilter = false;
120   if (spec[0] == '-') {
121     spec.replace(0, 1, "");
122     isNegativeFilter = true;
123   }
124   if (!re.Init(spec, &error_msg)) {
125     Err << "Could not compile benchmark re: " << error_msg << std::endl;
126     return false;
127   }
128 
129   // Special list of thread counts to use when none are specified
130   const std::vector<int> one_thread = {1};
131 
132   int next_family_index = 0;
133 
134   MutexLock l(mutex_);
135   for (std::unique_ptr<Benchmark>& family : families_) {
136     int family_index = next_family_index;
137     int per_family_instance_index = 0;
138 
139     // Family was deleted or benchmark doesn't match
140     if (!family) continue;
141 
142     if (family->ArgsCnt() == -1) {
143       family->Args({});
144     }
145     const std::vector<int>* thread_counts =
146         (family->thread_counts_.empty()
147              ? &one_thread
148              : &static_cast<const std::vector<int>&>(family->thread_counts_));
149     const size_t family_size = family->args_.size() * thread_counts->size();
150     // The benchmark will be run at least 'family_size' different inputs.
151     // If 'family_size' is very large warn the user.
152     if (family_size > kMaxFamilySize) {
153       Err << "The number of inputs is very large. " << family->name_
154           << " will be repeated at least " << family_size << " times.\n";
155     }
156     // reserve in the special case the regex ".", since we know the final
157     // family size.
158     if (spec == ".") benchmarks->reserve(benchmarks->size() + family_size);
159 
160     for (auto const& args : family->args_) {
161       for (int num_threads : *thread_counts) {
162         BenchmarkInstance instance(family.get(), family_index,
163                                    per_family_instance_index, args,
164                                    num_threads);
165 
166         const auto full_name = instance.name().str();
167         if ((re.Match(full_name) && !isNegativeFilter) ||
168             (!re.Match(full_name) && isNegativeFilter)) {
169           benchmarks->push_back(std::move(instance));
170 
171           ++per_family_instance_index;
172 
173           // Only bump the next family index once we've estabilished that
174           // at least one instance of this family will be run.
175           if (next_family_index == family_index) ++next_family_index;
176         }
177       }
178     }
179   }
180   return true;
181 }
182 
RegisterBenchmarkInternal(Benchmark * bench)183 Benchmark* RegisterBenchmarkInternal(Benchmark* bench) {
184   std::unique_ptr<Benchmark> bench_ptr(bench);
185   BenchmarkFamilies* families = BenchmarkFamilies::GetInstance();
186   families->AddBenchmark(std::move(bench_ptr));
187   return bench;
188 }
189 
190 // FIXME: This function is a hack so that benchmark.cc can access
191 // `BenchmarkFamilies`
FindBenchmarksInternal(const std::string & re,std::vector<BenchmarkInstance> * benchmarks,std::ostream * Err)192 bool FindBenchmarksInternal(const std::string& re,
193                             std::vector<BenchmarkInstance>* benchmarks,
194                             std::ostream* Err) {
195   return BenchmarkFamilies::GetInstance()->FindBenchmarks(re, benchmarks, Err);
196 }
197 
198 //=============================================================================//
199 //                               Benchmark
200 //=============================================================================//
201 
Benchmark(const char * name)202 Benchmark::Benchmark(const char* name)
203     : name_(name),
204       aggregation_report_mode_(ARM_Unspecified),
205       time_unit_(kNanosecond),
206       range_multiplier_(kRangeMultiplier),
207       min_time_(0),
208       iterations_(0),
209       repetitions_(0),
210       measure_process_cpu_time_(false),
211       use_real_time_(false),
212       use_manual_time_(false),
213       complexity_(oNone),
214       complexity_lambda_(nullptr) {
215   ComputeStatistics("mean", StatisticsMean);
216   ComputeStatistics("median", StatisticsMedian);
217   ComputeStatistics("stddev", StatisticsStdDev);
218   ComputeStatistics("cv", StatisticsCV, kPercentage);
219 }
220 
~Benchmark()221 Benchmark::~Benchmark() {}
222 
Name(const std::string & name)223 Benchmark* Benchmark::Name(const std::string& name) {
224   SetName(name.c_str());
225   return this;
226 }
227 
Arg(int64_t x)228 Benchmark* Benchmark::Arg(int64_t x) {
229   BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);
230   args_.push_back({x});
231   return this;
232 }
233 
Unit(TimeUnit unit)234 Benchmark* Benchmark::Unit(TimeUnit unit) {
235   time_unit_ = unit;
236   return this;
237 }
238 
Range(int64_t start,int64_t limit)239 Benchmark* Benchmark::Range(int64_t start, int64_t limit) {
240   BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);
241   std::vector<int64_t> arglist;
242   AddRange(&arglist, start, limit, range_multiplier_);
243 
244   for (int64_t i : arglist) {
245     args_.push_back({i});
246   }
247   return this;
248 }
249 
Ranges(const std::vector<std::pair<int64_t,int64_t>> & ranges)250 Benchmark* Benchmark::Ranges(
251     const std::vector<std::pair<int64_t, int64_t>>& ranges) {
252   BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(ranges.size()));
253   std::vector<std::vector<int64_t>> arglists(ranges.size());
254   for (std::size_t i = 0; i < ranges.size(); i++) {
255     AddRange(&arglists[i], ranges[i].first, ranges[i].second,
256              range_multiplier_);
257   }
258 
259   ArgsProduct(arglists);
260 
261   return this;
262 }
263 
ArgsProduct(const std::vector<std::vector<int64_t>> & arglists)264 Benchmark* Benchmark::ArgsProduct(
265     const std::vector<std::vector<int64_t>>& arglists) {
266   BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(arglists.size()));
267 
268   std::vector<std::size_t> indices(arglists.size());
269   const std::size_t total = std::accumulate(
270       std::begin(arglists), std::end(arglists), std::size_t{1},
271       [](const std::size_t res, const std::vector<int64_t>& arglist) {
272         return res * arglist.size();
273       });
274   std::vector<int64_t> args;
275   args.reserve(arglists.size());
276   for (std::size_t i = 0; i < total; i++) {
277     for (std::size_t arg = 0; arg < arglists.size(); arg++) {
278       args.push_back(arglists[arg][indices[arg]]);
279     }
280     args_.push_back(args);
281     args.clear();
282 
283     std::size_t arg = 0;
284     do {
285       indices[arg] = (indices[arg] + 1) % arglists[arg].size();
286     } while (indices[arg++] == 0 && arg < arglists.size());
287   }
288 
289   return this;
290 }
291 
ArgName(const std::string & name)292 Benchmark* Benchmark::ArgName(const std::string& name) {
293   BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);
294   arg_names_ = {name};
295   return this;
296 }
297 
ArgNames(const std::vector<std::string> & names)298 Benchmark* Benchmark::ArgNames(const std::vector<std::string>& names) {
299   BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(names.size()));
300   arg_names_ = names;
301   return this;
302 }
303 
DenseRange(int64_t start,int64_t limit,int step)304 Benchmark* Benchmark::DenseRange(int64_t start, int64_t limit, int step) {
305   BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);
306   BM_CHECK_LE(start, limit);
307   for (int64_t arg = start; arg <= limit; arg += step) {
308     args_.push_back({arg});
309   }
310   return this;
311 }
312 
Args(const std::vector<int64_t> & args)313 Benchmark* Benchmark::Args(const std::vector<int64_t>& args) {
314   BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(args.size()));
315   args_.push_back(args);
316   return this;
317 }
318 
Apply(void (* custom_arguments)(Benchmark * benchmark))319 Benchmark* Benchmark::Apply(void (*custom_arguments)(Benchmark* benchmark)) {
320   custom_arguments(this);
321   return this;
322 }
323 
RangeMultiplier(int multiplier)324 Benchmark* Benchmark::RangeMultiplier(int multiplier) {
325   BM_CHECK(multiplier > 1);
326   range_multiplier_ = multiplier;
327   return this;
328 }
329 
MinTime(double t)330 Benchmark* Benchmark::MinTime(double t) {
331   BM_CHECK(t > 0.0);
332   BM_CHECK(iterations_ == 0);
333   min_time_ = t;
334   return this;
335 }
336 
Iterations(IterationCount n)337 Benchmark* Benchmark::Iterations(IterationCount n) {
338   BM_CHECK(n > 0);
339   BM_CHECK(IsZero(min_time_));
340   iterations_ = n;
341   return this;
342 }
343 
Repetitions(int n)344 Benchmark* Benchmark::Repetitions(int n) {
345   BM_CHECK(n > 0);
346   repetitions_ = n;
347   return this;
348 }
349 
ReportAggregatesOnly(bool value)350 Benchmark* Benchmark::ReportAggregatesOnly(bool value) {
351   aggregation_report_mode_ = value ? ARM_ReportAggregatesOnly : ARM_Default;
352   return this;
353 }
354 
DisplayAggregatesOnly(bool value)355 Benchmark* Benchmark::DisplayAggregatesOnly(bool value) {
356   // If we were called, the report mode is no longer 'unspecified', in any case.
357   aggregation_report_mode_ = static_cast<AggregationReportMode>(
358       aggregation_report_mode_ | ARM_Default);
359 
360   if (value) {
361     aggregation_report_mode_ = static_cast<AggregationReportMode>(
362         aggregation_report_mode_ | ARM_DisplayReportAggregatesOnly);
363   } else {
364     aggregation_report_mode_ = static_cast<AggregationReportMode>(
365         aggregation_report_mode_ & ~ARM_DisplayReportAggregatesOnly);
366   }
367 
368   return this;
369 }
370 
MeasureProcessCPUTime()371 Benchmark* Benchmark::MeasureProcessCPUTime() {
372   // Can be used together with UseRealTime() / UseManualTime().
373   measure_process_cpu_time_ = true;
374   return this;
375 }
376 
UseRealTime()377 Benchmark* Benchmark::UseRealTime() {
378   BM_CHECK(!use_manual_time_)
379       << "Cannot set UseRealTime and UseManualTime simultaneously.";
380   use_real_time_ = true;
381   return this;
382 }
383 
UseManualTime()384 Benchmark* Benchmark::UseManualTime() {
385   BM_CHECK(!use_real_time_)
386       << "Cannot set UseRealTime and UseManualTime simultaneously.";
387   use_manual_time_ = true;
388   return this;
389 }
390 
Complexity(BigO complexity)391 Benchmark* Benchmark::Complexity(BigO complexity) {
392   complexity_ = complexity;
393   return this;
394 }
395 
Complexity(BigOFunc * complexity)396 Benchmark* Benchmark::Complexity(BigOFunc* complexity) {
397   complexity_lambda_ = complexity;
398   complexity_ = oLambda;
399   return this;
400 }
401 
ComputeStatistics(std::string name,StatisticsFunc * statistics,StatisticUnit unit)402 Benchmark* Benchmark::ComputeStatistics(std::string name,
403                                         StatisticsFunc* statistics,
404                                         StatisticUnit unit) {
405   statistics_.emplace_back(name, statistics, unit);
406   return this;
407 }
408 
Threads(int t)409 Benchmark* Benchmark::Threads(int t) {
410   BM_CHECK_GT(t, 0);
411   thread_counts_.push_back(t);
412   return this;
413 }
414 
ThreadRange(int min_threads,int max_threads)415 Benchmark* Benchmark::ThreadRange(int min_threads, int max_threads) {
416   BM_CHECK_GT(min_threads, 0);
417   BM_CHECK_GE(max_threads, min_threads);
418 
419   AddRange(&thread_counts_, min_threads, max_threads, 2);
420   return this;
421 }
422 
DenseThreadRange(int min_threads,int max_threads,int stride)423 Benchmark* Benchmark::DenseThreadRange(int min_threads, int max_threads,
424                                        int stride) {
425   BM_CHECK_GT(min_threads, 0);
426   BM_CHECK_GE(max_threads, min_threads);
427   BM_CHECK_GE(stride, 1);
428 
429   for (auto i = min_threads; i < max_threads; i += stride) {
430     thread_counts_.push_back(i);
431   }
432   thread_counts_.push_back(max_threads);
433   return this;
434 }
435 
ThreadPerCpu()436 Benchmark* Benchmark::ThreadPerCpu() {
437   thread_counts_.push_back(CPUInfo::Get().num_cpus);
438   return this;
439 }
440 
SetName(const char * name)441 void Benchmark::SetName(const char* name) { name_ = name; }
442 
ArgsCnt() const443 int Benchmark::ArgsCnt() const {
444   if (args_.empty()) {
445     if (arg_names_.empty()) return -1;
446     return static_cast<int>(arg_names_.size());
447   }
448   return static_cast<int>(args_.front().size());
449 }
450 
451 //=============================================================================//
452 //                            FunctionBenchmark
453 //=============================================================================//
454 
Run(State & st)455 void FunctionBenchmark::Run(State& st) { func_(st); }
456 
457 }  // end namespace internal
458 
ClearRegisteredBenchmarks()459 void ClearRegisteredBenchmarks() {
460   internal::BenchmarkFamilies::GetInstance()->ClearBenchmarks();
461 }
462 
CreateRange(int64_t lo,int64_t hi,int multi)463 std::vector<int64_t> CreateRange(int64_t lo, int64_t hi, int multi) {
464   std::vector<int64_t> args;
465   internal::AddRange(&args, lo, hi, multi);
466   return args;
467 }
468 
CreateDenseRange(int64_t start,int64_t limit,int step)469 std::vector<int64_t> CreateDenseRange(int64_t start, int64_t limit,
470                                       int step) {
471   BM_CHECK_LE(start, limit);
472   std::vector<int64_t> args;
473   for (int64_t arg = start; arg <= limit; arg += step) {
474     args.push_back(arg);
475   }
476   return args;
477 }
478 
479 }  // end namespace benchmark
480