Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(607)

Side by Side Diff: third_party/google_benchmark/src/benchmark_register.cc

Issue 2865663003: Adding Google benchmarking library. (Closed)
Patch Set: Sketch. Created 3 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
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 // Extract the list of benchmark instances that match the specified
74 // regular expression.
75 bool FindBenchmarks(const std::string& re,
76 std::vector<Benchmark::Instance>* benchmarks,
77 std::ostream* Err);
78
79 private:
80 BenchmarkFamilies() {}
81
82 std::vector<std::unique_ptr<Benchmark>> families_;
83 Mutex mutex_;
84 };
85
86 BenchmarkFamilies* BenchmarkFamilies::GetInstance() {
87 static BenchmarkFamilies instance;
88 return &instance;
89 }
90
91 size_t BenchmarkFamilies::AddBenchmark(std::unique_ptr<Benchmark> family) {
92 MutexLock l(mutex_);
93 size_t index = families_.size();
94 families_.push_back(std::move(family));
95 return index;
96 }
97
98 bool BenchmarkFamilies::FindBenchmarks(
99 const std::string& spec, std::vector<Benchmark::Instance>* benchmarks,
100 std::ostream* ErrStream) {
101 CHECK(ErrStream);
102 auto& Err = *ErrStream;
103 // Make regular expression out of command-line flag
104 std::string error_msg;
105 Regex re;
106 if (!re.Init(spec, &error_msg)) {
107 Err << "Could not compile benchmark re: " << error_msg << std::endl;
108 return false;
109 }
110
111 // Special list of thread counts to use when none are specified
112 const std::vector<int> one_thread = {1};
113
114 MutexLock l(mutex_);
115 for (std::unique_ptr<Benchmark>& family : families_) {
116 // Family was deleted or benchmark doesn't match
117 if (!family) continue;
118
119 if (family->ArgsCnt() == -1) {
120 family->Args({});
121 }
122 const std::vector<int>* thread_counts =
123 (family->thread_counts_.empty()
124 ? &one_thread
125 : &static_cast<const std::vector<int>&>(family->thread_counts_));
126 const size_t family_size = family->args_.size() * thread_counts->size();
127 // The benchmark will be run at least 'family_size' different inputs.
128 // If 'family_size' is very large warn the user.
129 if (family_size > kMaxFamilySize) {
130 Err << "The number of inputs is very large. " << family->name_
131 << " will be repeated at least " << family_size << " times.\n";
132 }
133 // reserve in the special case the regex ".", since we know the final
134 // family size.
135 if (spec == ".") benchmarks->reserve(family_size);
136
137 for (auto const& args : family->args_) {
138 for (int num_threads : *thread_counts) {
139 Benchmark::Instance instance;
140 instance.name = family->name_;
141 instance.benchmark = family.get();
142 instance.report_mode = family->report_mode_;
143 instance.arg = args;
144 instance.time_unit = family->time_unit_;
145 instance.range_multiplier = family->range_multiplier_;
146 instance.min_time = family->min_time_;
147 instance.iterations = family->iterations_;
148 instance.repetitions = family->repetitions_;
149 instance.use_real_time = family->use_real_time_;
150 instance.use_manual_time = family->use_manual_time_;
151 instance.complexity = family->complexity_;
152 instance.complexity_lambda = family->complexity_lambda_;
153 instance.threads = num_threads;
154
155 // Add arguments to instance name
156 size_t arg_i = 0;
157 for (auto const& arg : args) {
158 instance.name += "/";
159
160 if (arg_i < family->arg_names_.size()) {
161 const auto& arg_name = family->arg_names_[arg_i];
162 if (!arg_name.empty()) {
163 instance.name +=
164 StringPrintF("%s:", family->arg_names_[arg_i].c_str());
165 }
166 }
167
168 instance.name += StringPrintF("%d", arg);
169 ++arg_i;
170 }
171
172 if (!IsZero(family->min_time_))
173 instance.name += StringPrintF("/min_time:%0.3f", family->min_time_);
174 if (family->iterations_ != 0)
175 instance.name += StringPrintF("/iterations:%d", family->iterations_);
176 if (family->repetitions_ != 0)
177 instance.name += StringPrintF("/repeats:%d", family->repetitions_);
178
179 if (family->use_manual_time_) {
180 instance.name += "/manual_time";
181 } else if (family->use_real_time_) {
182 instance.name += "/real_time";
183 }
184
185 // Add the number of threads used to the name
186 if (!family->thread_counts_.empty()) {
187 instance.name += StringPrintF("/threads:%d", instance.threads);
188 }
189
190 if (re.Match(instance.name)) {
191 instance.last_benchmark_instance = (&args == &family->args_.back());
192 benchmarks->push_back(std::move(instance));
193 }
194 }
195 }
196 }
197 return true;
198 }
199
200 Benchmark* RegisterBenchmarkInternal(Benchmark* bench) {
201 std::unique_ptr<Benchmark> bench_ptr(bench);
202 BenchmarkFamilies* families = BenchmarkFamilies::GetInstance();
203 families->AddBenchmark(std::move(bench_ptr));
204 return bench;
205 }
206
207 // FIXME: This function is a hack so that benchmark.cc can access
208 // `BenchmarkFamilies`
209 bool FindBenchmarksInternal(const std::string& re,
210 std::vector<Benchmark::Instance>* benchmarks,
211 std::ostream* Err) {
212 return BenchmarkFamilies::GetInstance()->FindBenchmarks(re, benchmarks, Err);
213 }
214
215 //=============================================================================/ /
216 // Benchmark
217 //=============================================================================/ /
218
219 Benchmark::Benchmark(const char* name)
220 : name_(name),
221 report_mode_(RM_Unspecified),
222 time_unit_(kNanosecond),
223 range_multiplier_(kRangeMultiplier),
224 min_time_(0),
225 iterations_(0),
226 repetitions_(0),
227 use_real_time_(false),
228 use_manual_time_(false),
229 complexity_(oNone),
230 complexity_lambda_(nullptr) {}
231
232 Benchmark::~Benchmark() {}
233
234 void Benchmark::AddRange(std::vector<int>* dst, int lo, int hi, int mult) {
235 CHECK_GE(lo, 0);
236 CHECK_GE(hi, lo);
237 CHECK_GE(mult, 2);
238
239 // Add "lo"
240 dst->push_back(lo);
241
242 static const int kint32max = std::numeric_limits<int32_t>::max();
243
244 // Now space out the benchmarks in multiples of "mult"
245 for (int32_t i = 1; i < kint32max / mult; i *= mult) {
246 if (i >= hi) break;
247 if (i > lo) {
248 dst->push_back(i);
249 }
250 }
251 // Add "hi" (if different from "lo")
252 if (hi != lo) {
253 dst->push_back(hi);
254 }
255 }
256
257 Benchmark* Benchmark::Arg(int x) {
258 CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);
259 args_.push_back({x});
260 return this;
261 }
262
263 Benchmark* Benchmark::Unit(TimeUnit unit) {
264 time_unit_ = unit;
265 return this;
266 }
267
268 Benchmark* Benchmark::Range(int start, int limit) {
269 CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);
270 std::vector<int> arglist;
271 AddRange(&arglist, start, limit, range_multiplier_);
272
273 for (int i : arglist) {
274 args_.push_back({i});
275 }
276 return this;
277 }
278
279 Benchmark* Benchmark::Ranges(const std::vector<std::pair<int, int>>& ranges) {
280 CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(ranges.size()));
281 std::vector<std::vector<int>> arglists(ranges.size());
282 std::size_t total = 1;
283 for (std::size_t i = 0; i < ranges.size(); i++) {
284 AddRange(&arglists[i], ranges[i].first, ranges[i].second,
285 range_multiplier_);
286 total *= arglists[i].size();
287 }
288
289 std::vector<std::size_t> ctr(arglists.size(), 0);
290
291 for (std::size_t i = 0; i < total; i++) {
292 std::vector<int> tmp;
293 tmp.reserve(arglists.size());
294
295 for (std::size_t j = 0; j < arglists.size(); j++) {
296 tmp.push_back(arglists[j].at(ctr[j]));
297 }
298
299 args_.push_back(std::move(tmp));
300
301 for (std::size_t j = 0; j < arglists.size(); j++) {
302 if (ctr[j] + 1 < arglists[j].size()) {
303 ++ctr[j];
304 break;
305 }
306 ctr[j] = 0;
307 }
308 }
309 return this;
310 }
311
312 Benchmark* Benchmark::ArgName(const std::string& name) {
313 CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);
314 arg_names_ = {name};
315 return this;
316 }
317
318 Benchmark* Benchmark::ArgNames(const std::vector<std::string>& names) {
319 CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(names.size()));
320 arg_names_ = names;
321 return this;
322 }
323
324 Benchmark* Benchmark::DenseRange(int start, int limit, int step) {
325 CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);
326 CHECK_GE(start, 0);
327 CHECK_LE(start, limit);
328 for (int arg = start; arg <= limit; arg += step) {
329 args_.push_back({arg});
330 }
331 return this;
332 }
333
334 Benchmark* Benchmark::Args(const std::vector<int>& args) {
335 CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(args.size()));
336 args_.push_back(args);
337 return this;
338 }
339
340 Benchmark* Benchmark::Apply(void (*custom_arguments)(Benchmark* benchmark)) {
341 custom_arguments(this);
342 return this;
343 }
344
345 Benchmark* Benchmark::RangeMultiplier(int multiplier) {
346 CHECK(multiplier > 1);
347 range_multiplier_ = multiplier;
348 return this;
349 }
350
351
352 Benchmark* Benchmark::MinTime(double t) {
353 CHECK(t > 0.0);
354 CHECK(iterations_ == 0);
355 min_time_ = t;
356 return this;
357 }
358
359
360 Benchmark* Benchmark::Iterations(size_t n) {
361 CHECK(n > 0);
362 CHECK(IsZero(min_time_));
363 iterations_ = n;
364 return this;
365 }
366
367 Benchmark* Benchmark::Repetitions(int n) {
368 CHECK(n > 0);
369 repetitions_ = n;
370 return this;
371 }
372
373 Benchmark* Benchmark::ReportAggregatesOnly(bool value) {
374 report_mode_ = value ? RM_ReportAggregatesOnly : RM_Default;
375 return this;
376 }
377
378 Benchmark* Benchmark::UseRealTime() {
379 CHECK(!use_manual_time_)
380 << "Cannot set UseRealTime and UseManualTime simultaneously.";
381 use_real_time_ = true;
382 return this;
383 }
384
385 Benchmark* Benchmark::UseManualTime() {
386 CHECK(!use_real_time_)
387 << "Cannot set UseRealTime and UseManualTime simultaneously.";
388 use_manual_time_ = true;
389 return this;
390 }
391
392 Benchmark* Benchmark::Complexity(BigO complexity) {
393 complexity_ = complexity;
394 return this;
395 }
396
397 Benchmark* Benchmark::Complexity(BigOFunc* complexity) {
398 complexity_lambda_ = complexity;
399 complexity_ = oLambda;
400 return this;
401 }
402
403 Benchmark* Benchmark::Threads(int t) {
404 CHECK_GT(t, 0);
405 thread_counts_.push_back(t);
406 return this;
407 }
408
409 Benchmark* Benchmark::ThreadRange(int min_threads, int max_threads) {
410 CHECK_GT(min_threads, 0);
411 CHECK_GE(max_threads, min_threads);
412
413 AddRange(&thread_counts_, min_threads, max_threads, 2);
414 return this;
415 }
416
417 Benchmark* Benchmark::DenseThreadRange(int min_threads, int max_threads,
418 int stride) {
419 CHECK_GT(min_threads, 0);
420 CHECK_GE(max_threads, min_threads);
421 CHECK_GE(stride, 1);
422
423 for (auto i = min_threads; i < max_threads; i += stride) {
424 thread_counts_.push_back(i);
425 }
426 thread_counts_.push_back(max_threads);
427 return this;
428 }
429
430 Benchmark* Benchmark::ThreadPerCpu() {
431 static int num_cpus = NumCPUs();
432 thread_counts_.push_back(num_cpus);
433 return this;
434 }
435
436 void Benchmark::SetName(const char* name) { name_ = name; }
437
438 int Benchmark::ArgsCnt() const {
439 if (args_.empty()) {
440 if (arg_names_.empty()) return -1;
441 return static_cast<int>(arg_names_.size());
442 }
443 return static_cast<int>(args_.front().size());
444 }
445
446 //=============================================================================/ /
447 // FunctionBenchmark
448 //=============================================================================/ /
449
450 void FunctionBenchmark::Run(State& st) { func_(st); }
451
452 } // end namespace internal
453 } // end namespace benchmark
OLDNEW
« no previous file with comments | « third_party/google_benchmark/src/benchmark_api_internal.h ('k') | third_party/google_benchmark/src/check.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698