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