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   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 }
219 
~Benchmark()220 Benchmark::~Benchmark() {}
221 
Name(const std::string & name)222 Benchmark* Benchmark::Name(const std::string& name) {
223   SetName(name.c_str());
224   return this;
225 }
226 
Arg(int64_t x)227 Benchmark* Benchmark::Arg(int64_t x) {
228   CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);
229   args_.push_back({x});
230   return this;
231 }
232 
Unit(TimeUnit unit)233 Benchmark* Benchmark::Unit(TimeUnit unit) {
234   time_unit_ = unit;
235   return this;
236 }
237 
Range(int64_t start,int64_t limit)238 Benchmark* Benchmark::Range(int64_t start, int64_t limit) {
239   CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);
240   std::vector<int64_t> arglist;
241   AddRange(&arglist, start, limit, range_multiplier_);
242 
243   for (int64_t i : arglist) {
244     args_.push_back({i});
245   }
246   return this;
247 }
248 
Ranges(const std::vector<std::pair<int64_t,int64_t>> & ranges)249 Benchmark* Benchmark::Ranges(
250     const std::vector<std::pair<int64_t, int64_t>>& ranges) {
251   CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(ranges.size()));
252   std::vector<std::vector<int64_t>> arglists(ranges.size());
253   for (std::size_t i = 0; i < ranges.size(); i++) {
254     AddRange(&arglists[i], ranges[i].first, ranges[i].second,
255              range_multiplier_);
256   }
257 
258   ArgsProduct(arglists);
259 
260   return this;
261 }
262 
ArgsProduct(const std::vector<std::vector<int64_t>> & arglists)263 Benchmark* Benchmark::ArgsProduct(
264     const std::vector<std::vector<int64_t>>& arglists) {
265   CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(arglists.size()));
266 
267   std::vector<std::size_t> indices(arglists.size());
268   const std::size_t total = std::accumulate(
269       std::begin(arglists), std::end(arglists), std::size_t{1},
270       [](const std::size_t res, const std::vector<int64_t>& arglist) {
271         return res * arglist.size();
272       });
273   std::vector<int64_t> args;
274   args.reserve(arglists.size());
275   for (std::size_t i = 0; i < total; i++) {
276     for (std::size_t arg = 0; arg < arglists.size(); arg++) {
277       args.push_back(arglists[arg][indices[arg]]);
278     }
279     args_.push_back(args);
280     args.clear();
281 
282     std::size_t arg = 0;
283     do {
284       indices[arg] = (indices[arg] + 1) % arglists[arg].size();
285     } while (indices[arg++] == 0 && arg < arglists.size());
286   }
287 
288   return this;
289 }
290 
ArgName(const std::string & name)291 Benchmark* Benchmark::ArgName(const std::string& name) {
292   CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);
293   arg_names_ = {name};
294   return this;
295 }
296 
ArgNames(const std::vector<std::string> & names)297 Benchmark* Benchmark::ArgNames(const std::vector<std::string>& names) {
298   CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(names.size()));
299   arg_names_ = names;
300   return this;
301 }
302 
DenseRange(int64_t start,int64_t limit,int step)303 Benchmark* Benchmark::DenseRange(int64_t start, int64_t limit, int step) {
304   CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);
305   CHECK_LE(start, limit);
306   for (int64_t arg = start; arg <= limit; arg += step) {
307     args_.push_back({arg});
308   }
309   return this;
310 }
311 
Args(const std::vector<int64_t> & args)312 Benchmark* Benchmark::Args(const std::vector<int64_t>& args) {
313   CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(args.size()));
314   args_.push_back(args);
315   return this;
316 }
317 
Apply(void (* custom_arguments)(Benchmark * benchmark))318 Benchmark* Benchmark::Apply(void (*custom_arguments)(Benchmark* benchmark)) {
319   custom_arguments(this);
320   return this;
321 }
322 
RangeMultiplier(int multiplier)323 Benchmark* Benchmark::RangeMultiplier(int multiplier) {
324   CHECK(multiplier > 1);
325   range_multiplier_ = multiplier;
326   return this;
327 }
328 
MinTime(double t)329 Benchmark* Benchmark::MinTime(double t) {
330   CHECK(t > 0.0);
331   CHECK(iterations_ == 0);
332   min_time_ = t;
333   return this;
334 }
335 
Iterations(IterationCount n)336 Benchmark* Benchmark::Iterations(IterationCount n) {
337   CHECK(n > 0);
338   CHECK(IsZero(min_time_));
339   iterations_ = n;
340   return this;
341 }
342 
Repetitions(int n)343 Benchmark* Benchmark::Repetitions(int n) {
344   CHECK(n > 0);
345   repetitions_ = n;
346   return this;
347 }
348 
ReportAggregatesOnly(bool value)349 Benchmark* Benchmark::ReportAggregatesOnly(bool value) {
350   aggregation_report_mode_ = value ? ARM_ReportAggregatesOnly : ARM_Default;
351   return this;
352 }
353 
DisplayAggregatesOnly(bool value)354 Benchmark* Benchmark::DisplayAggregatesOnly(bool value) {
355   // If we were called, the report mode is no longer 'unspecified', in any case.
356   aggregation_report_mode_ = static_cast<AggregationReportMode>(
357       aggregation_report_mode_ | ARM_Default);
358 
359   if (value) {
360     aggregation_report_mode_ = static_cast<AggregationReportMode>(
361         aggregation_report_mode_ | ARM_DisplayReportAggregatesOnly);
362   } else {
363     aggregation_report_mode_ = static_cast<AggregationReportMode>(
364         aggregation_report_mode_ & ~ARM_DisplayReportAggregatesOnly);
365   }
366 
367   return this;
368 }
369 
MeasureProcessCPUTime()370 Benchmark* Benchmark::MeasureProcessCPUTime() {
371   // Can be used together with UseRealTime() / UseManualTime().
372   measure_process_cpu_time_ = true;
373   return this;
374 }
375 
UseRealTime()376 Benchmark* Benchmark::UseRealTime() {
377   CHECK(!use_manual_time_)
378       << "Cannot set UseRealTime and UseManualTime simultaneously.";
379   use_real_time_ = true;
380   return this;
381 }
382 
UseManualTime()383 Benchmark* Benchmark::UseManualTime() {
384   CHECK(!use_real_time_)
385       << "Cannot set UseRealTime and UseManualTime simultaneously.";
386   use_manual_time_ = true;
387   return this;
388 }
389 
Complexity(BigO complexity)390 Benchmark* Benchmark::Complexity(BigO complexity) {
391   complexity_ = complexity;
392   return this;
393 }
394 
Complexity(BigOFunc * complexity)395 Benchmark* Benchmark::Complexity(BigOFunc* complexity) {
396   complexity_lambda_ = complexity;
397   complexity_ = oLambda;
398   return this;
399 }
400 
ComputeStatistics(std::string name,StatisticsFunc * statistics)401 Benchmark* Benchmark::ComputeStatistics(std::string name,
402                                         StatisticsFunc* statistics) {
403   statistics_.emplace_back(name, statistics);
404   return this;
405 }
406 
Threads(int t)407 Benchmark* Benchmark::Threads(int t) {
408   CHECK_GT(t, 0);
409   thread_counts_.push_back(t);
410   return this;
411 }
412 
ThreadRange(int min_threads,int max_threads)413 Benchmark* Benchmark::ThreadRange(int min_threads, int max_threads) {
414   CHECK_GT(min_threads, 0);
415   CHECK_GE(max_threads, min_threads);
416 
417   AddRange(&thread_counts_, min_threads, max_threads, 2);
418   return this;
419 }
420 
DenseThreadRange(int min_threads,int max_threads,int stride)421 Benchmark* Benchmark::DenseThreadRange(int min_threads, int max_threads,
422                                        int stride) {
423   CHECK_GT(min_threads, 0);
424   CHECK_GE(max_threads, min_threads);
425   CHECK_GE(stride, 1);
426 
427   for (auto i = min_threads; i < max_threads; i += stride) {
428     thread_counts_.push_back(i);
429   }
430   thread_counts_.push_back(max_threads);
431   return this;
432 }
433 
ThreadPerCpu()434 Benchmark* Benchmark::ThreadPerCpu() {
435   thread_counts_.push_back(CPUInfo::Get().num_cpus);
436   return this;
437 }
438 
SetName(const char * name)439 void Benchmark::SetName(const char* name) { name_ = name; }
440 
ArgsCnt() const441 int Benchmark::ArgsCnt() const {
442   if (args_.empty()) {
443     if (arg_names_.empty()) return -1;
444     return static_cast<int>(arg_names_.size());
445   }
446   return static_cast<int>(args_.front().size());
447 }
448 
449 //=============================================================================//
450 //                            FunctionBenchmark
451 //=============================================================================//
452 
Run(State & st)453 void FunctionBenchmark::Run(State& st) { func_(st); }
454 
455 }  // end namespace internal
456 
ClearRegisteredBenchmarks()457 void ClearRegisteredBenchmarks() {
458   internal::BenchmarkFamilies::GetInstance()->ClearBenchmarks();
459 }
460 
461 }  // end namespace benchmark
462