blob: 1a7d218283ce377a2bcfa906cbe33065c7cd0655 [file] [log] [blame]
Eric Fiselierb08d8b12016-07-19 23:07:03 +00001// 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"
Eric Fiselierfbc9ff22016-11-05 00:30:27 +000016#include "benchmark_api_internal.h"
Eric Fiselierb08d8b12016-07-19 23:07:03 +000017#include "internal_macros.h"
18
19#ifndef BENCHMARK_OS_WINDOWS
Eric Fiselierb08d8b12016-07-19 23:07:03 +000020#include <sys/resource.h>
Eric Fiselierfbc9ff22016-11-05 00:30:27 +000021#include <sys/time.h>
Eric Fiselierb08d8b12016-07-19 23:07:03 +000022#include <unistd.h>
23#endif
24
Eric Fiselierb08d8b12016-07-19 23:07:03 +000025#include <algorithm>
26#include <atomic>
27#include <condition_variable>
Eric Fiselierfbc9ff22016-11-05 00:30:27 +000028#include <cstdio>
29#include <cstdlib>
30#include <cstring>
Eric Fiselierf6e09e52016-08-09 18:56:48 +000031#include <fstream>
Eric Fiselierfbc9ff22016-11-05 00:30:27 +000032#include <iostream>
Eric Fiselierb08d8b12016-07-19 23:07:03 +000033#include <memory>
34#include <thread>
35
36#include "check.h"
Eric Fiselierfbc9ff22016-11-05 00:30:27 +000037#include "colorprint.h"
Eric Fiselierb08d8b12016-07-19 23:07:03 +000038#include "commandlineflags.h"
39#include "complexity.h"
Eric Fiselier133a7202017-04-18 07:17:20 +000040#include "counter.h"
Eric Fiselier19039762018-01-18 04:23:01 +000041#include "internal_macros.h"
Eric Fiselierb08d8b12016-07-19 23:07:03 +000042#include "log.h"
43#include "mutex.h"
44#include "re.h"
Eric Fiselier19039762018-01-18 04:23:01 +000045#include "statistics.h"
Eric Fiselierb08d8b12016-07-19 23:07:03 +000046#include "string_util.h"
Eric Fiselierfbc9ff22016-11-05 00:30:27 +000047#include "timers.h"
Eric Fiselierb08d8b12016-07-19 23:07:03 +000048
49DEFINE_bool(benchmark_list_tests, false,
50 "Print a list of benchmarks. This option overrides all other "
51 "options.");
52
53DEFINE_string(benchmark_filter, ".",
54 "A regular expression that specifies the set of benchmarks "
55 "to execute. If this flag is empty, no benchmarks are run. "
56 "If this flag is the string \"all\", all benchmarks linked "
57 "into the process are run.");
58
59DEFINE_double(benchmark_min_time, 0.5,
60 "Minimum number of seconds we should run benchmark before "
61 "results are considered significant. For cpu-time based "
62 "tests, this is the lower bound on the total cpu time "
63 "used by all threads that make up the test. For real-time "
64 "based tests, this is the lower bound on the elapsed time "
65 "of the benchmark execution, regardless of number of "
66 "threads.");
67
68DEFINE_int32(benchmark_repetitions, 1,
69 "The number of runs of each benchmark. If greater than 1, the "
70 "mean and standard deviation of the runs will be reported.");
71
Eric Fiselier4d5e91d2016-08-29 19:12:01 +000072DEFINE_bool(benchmark_report_aggregates_only, false,
73 "Report the result of each benchmark repetitions. When 'true' is "
74 "specified only the mean, standard deviation, and other statistics "
75 "are reported for repeated benchmarks.");
76
Eric Fiselierb08d8b12016-07-19 23:07:03 +000077DEFINE_string(benchmark_format, "console",
78 "The format to use for console output. Valid values are "
79 "'console', 'json', or 'csv'.");
80
Eric Fiselierf6e09e52016-08-09 18:56:48 +000081DEFINE_string(benchmark_out_format, "json",
82 "The format to use for file output. Valid values are "
83 "'console', 'json', or 'csv'.");
84
85DEFINE_string(benchmark_out, "", "The file to write additonal output to");
86
Eric Fiselierfbc9ff22016-11-05 00:30:27 +000087DEFINE_string(benchmark_color, "auto",
88 "Whether to use colors in the output. Valid values: "
89 "'true'/'yes'/1, 'false'/'no'/0, and 'auto'. 'auto' means to use "
90 "colors if the output is being sent to a terminal and the TERM "
91 "environment variable is set to a terminal type that supports "
92 "colors.");
Eric Fiselierb08d8b12016-07-19 23:07:03 +000093
Eric Fiselier19039762018-01-18 04:23:01 +000094DEFINE_bool(benchmark_counters_tabular, false,
95 "Whether to use tabular format when printing user counters to "
96 "the console. Valid values: 'true'/'yes'/1, 'false'/'no'/0."
97 "Defaults to false.");
98
Eric Fiselierb08d8b12016-07-19 23:07:03 +000099DEFINE_int32(v, 0, "The level of verbose logging to output");
100
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000101namespace benchmark {
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000102
103namespace {
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000104static const size_t kMaxIterations = 1000000000;
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000105} // end namespace
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000106
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000107namespace internal {
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000108
Eric Fiselier19039762018-01-18 04:23:01 +0000109void UseCharPointer(char const volatile*) {}
110
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000111class ThreadManager {
112 public:
113 ThreadManager(int num_threads)
114 : alive_threads_(num_threads), start_stop_barrier_(num_threads) {}
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000115
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000116 Mutex& GetBenchmarkMutex() const RETURN_CAPABILITY(benchmark_mutex_) {
117 return benchmark_mutex_;
118 }
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000119
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000120 bool StartStopBarrier() EXCLUDES(end_cond_mutex_) {
121 return start_stop_barrier_.wait();
122 }
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000123
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000124 void NotifyThreadComplete() EXCLUDES(end_cond_mutex_) {
125 start_stop_barrier_.removeThread();
126 if (--alive_threads_ == 0) {
127 MutexLock lock(end_cond_mutex_);
128 end_condition_.notify_all();
129 }
130 }
131
132 void WaitForAllThreads() EXCLUDES(end_cond_mutex_) {
133 MutexLock lock(end_cond_mutex_);
134 end_condition_.wait(lock.native_handle(),
135 [this]() { return alive_threads_ == 0; });
136 }
137
138 public:
139 struct Result {
140 double real_time_used = 0;
141 double cpu_time_used = 0;
142 double manual_time_used = 0;
143 int64_t bytes_processed = 0;
144 int64_t items_processed = 0;
145 int complexity_n = 0;
146 std::string report_label_;
147 std::string error_message_;
148 bool has_error_ = false;
Eric Fiselier133a7202017-04-18 07:17:20 +0000149 UserCounters counters;
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000150 };
151 GUARDED_BY(GetBenchmarkMutex()) Result results;
152
153 private:
154 mutable Mutex benchmark_mutex_;
155 std::atomic<int> alive_threads_;
156 Barrier start_stop_barrier_;
157 Mutex end_cond_mutex_;
158 Condition end_condition_;
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000159};
160
161// Timer management class
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000162class ThreadTimer {
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000163 public:
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000164 ThreadTimer() = default;
165
166 // Called by each thread
167 void StartTimer() {
168 running_ = true;
169 start_real_time_ = ChronoClockNow();
170 start_cpu_time_ = ThreadCPUUsage();
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000171 }
172
173 // Called by each thread
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000174 void StopTimer() {
175 CHECK(running_);
176 running_ = false;
177 real_time_used_ += ChronoClockNow() - start_real_time_;
Eric Fiselier19039762018-01-18 04:23:01 +0000178 // Floating point error can result in the subtraction producing a negative
179 // time. Guard against that.
180 cpu_time_used_ += std::max<double>(ThreadCPUUsage() - start_cpu_time_, 0);
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000181 }
182
183 // Called by each thread
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000184 void SetIterationTime(double seconds) { manual_time_used_ += seconds; }
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000185
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000186 bool running() const { return running_; }
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000187
188 // REQUIRES: timer is not running
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000189 double real_time_used() {
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000190 CHECK(!running_);
191 return real_time_used_;
192 }
193
194 // REQUIRES: timer is not running
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000195 double cpu_time_used() {
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000196 CHECK(!running_);
197 return cpu_time_used_;
198 }
199
200 // REQUIRES: timer is not running
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000201 double manual_time_used() {
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000202 CHECK(!running_);
203 return manual_time_used_;
204 }
205
206 private:
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000207 bool running_ = false; // Is the timer running
208 double start_real_time_ = 0; // If running_
209 double start_cpu_time_ = 0; // If running_
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000210
211 // Accumulated time so far (does not contain current slice if running_)
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000212 double real_time_used_ = 0;
213 double cpu_time_used_ = 0;
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000214 // Manually set iteration time. User sets this with SetIterationTime(seconds).
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000215 double manual_time_used_ = 0;
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000216};
217
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000218namespace {
219
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000220BenchmarkReporter::Run CreateRunReport(
221 const benchmark::internal::Benchmark::Instance& b,
222 const internal::ThreadManager::Result& results, size_t iters,
223 double seconds) {
224 // Create report about this benchmark run.
225 BenchmarkReporter::Run report;
226
227 report.benchmark_name = b.name;
228 report.error_occurred = results.has_error_;
229 report.error_message = results.error_message_;
230 report.report_label = results.report_label_;
231 // Report the total iterations across all threads.
232 report.iterations = static_cast<int64_t>(iters) * b.threads;
233 report.time_unit = b.time_unit;
234
235 if (!report.error_occurred) {
236 double bytes_per_second = 0;
237 if (results.bytes_processed > 0 && seconds > 0.0) {
238 bytes_per_second = (results.bytes_processed / seconds);
239 }
240 double items_per_second = 0;
241 if (results.items_processed > 0 && seconds > 0.0) {
242 items_per_second = (results.items_processed / seconds);
243 }
244
245 if (b.use_manual_time) {
246 report.real_accumulated_time = results.manual_time_used;
247 } else {
248 report.real_accumulated_time = results.real_time_used;
249 }
250 report.cpu_accumulated_time = results.cpu_time_used;
251 report.bytes_per_second = bytes_per_second;
252 report.items_per_second = items_per_second;
253 report.complexity_n = results.complexity_n;
254 report.complexity = b.complexity;
255 report.complexity_lambda = b.complexity_lambda;
Eric Fiselier19039762018-01-18 04:23:01 +0000256 report.statistics = b.statistics;
Eric Fiselier133a7202017-04-18 07:17:20 +0000257 report.counters = results.counters;
Eric Fiselier19039762018-01-18 04:23:01 +0000258 internal::Finish(&report.counters, seconds, b.threads);
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000259 }
260 return report;
261}
262
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000263// Execute one thread of benchmark b for the specified number of iterations.
264// Adds the stats collected for the thread into *total.
265void RunInThread(const benchmark::internal::Benchmark::Instance* b,
266 size_t iters, int thread_id,
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000267 internal::ThreadManager* manager) {
268 internal::ThreadTimer timer;
269 State st(iters, b->arg, thread_id, b->threads, &timer, manager);
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000270 b->benchmark->Run(st);
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000271 CHECK(st.iterations() == st.max_iterations)
272 << "Benchmark returned before State::KeepRunning() returned false!";
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000273 {
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000274 MutexLock l(manager->GetBenchmarkMutex());
275 internal::ThreadManager::Result& results = manager->results;
276 results.cpu_time_used += timer.cpu_time_used();
277 results.real_time_used += timer.real_time_used();
278 results.manual_time_used += timer.manual_time_used();
279 results.bytes_processed += st.bytes_processed();
280 results.items_processed += st.items_processed();
281 results.complexity_n += st.complexity_length_n();
Eric Fiselier133a7202017-04-18 07:17:20 +0000282 internal::Increment(&results.counters, st.counters);
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000283 }
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000284 manager->NotifyThreadComplete();
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000285}
286
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000287std::vector<BenchmarkReporter::Run> RunBenchmark(
288 const benchmark::internal::Benchmark::Instance& b,
289 std::vector<BenchmarkReporter::Run>* complexity_reports) {
290 std::vector<BenchmarkReporter::Run> reports; // return value
Eric Fiselier4d5e91d2016-08-29 19:12:01 +0000291
Eric Fiselier133a7202017-04-18 07:17:20 +0000292 const bool has_explicit_iteration_count = b.iterations != 0;
293 size_t iters = has_explicit_iteration_count ? b.iterations : 1;
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000294 std::unique_ptr<internal::ThreadManager> manager;
295 std::vector<std::thread> pool(b.threads - 1);
296 const int repeats =
297 b.repetitions != 0 ? b.repetitions : FLAGS_benchmark_repetitions;
298 const bool report_aggregates_only =
299 repeats != 1 &&
Eric Fiselier4d5e91d2016-08-29 19:12:01 +0000300 (b.report_mode == internal::RM_Unspecified
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000301 ? FLAGS_benchmark_report_aggregates_only
302 : b.report_mode == internal::RM_ReportAggregatesOnly);
Eric Fiselier133a7202017-04-18 07:17:20 +0000303 for (int repetition_num = 0; repetition_num < repeats; repetition_num++) {
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000304 for (;;) {
305 // Try benchmark
306 VLOG(2) << "Running " << b.name << " for " << iters << "\n";
307
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000308 manager.reset(new internal::ThreadManager(b.threads));
309 for (std::size_t ti = 0; ti < pool.size(); ++ti) {
310 pool[ti] = std::thread(&RunInThread, &b, iters,
311 static_cast<int>(ti + 1), manager.get());
312 }
313 RunInThread(&b, iters, 0, manager.get());
314 manager->WaitForAllThreads();
315 for (std::thread& thread : pool) thread.join();
316 internal::ThreadManager::Result results;
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000317 {
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000318 MutexLock l(manager->GetBenchmarkMutex());
319 results = manager->results;
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000320 }
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000321 manager.reset();
322 // Adjust real/manual time stats since they were reported per thread.
323 results.real_time_used /= b.threads;
324 results.manual_time_used /= b.threads;
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000325
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000326 VLOG(2) << "Ran in " << results.cpu_time_used << "/"
327 << results.real_time_used << "\n";
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000328
329 // Base decisions off of real time if requested by this benchmark.
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000330 double seconds = results.cpu_time_used;
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000331 if (b.use_manual_time) {
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000332 seconds = results.manual_time_used;
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000333 } else if (b.use_real_time) {
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000334 seconds = results.real_time_used;
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000335 }
336
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000337 const double min_time =
338 !IsZero(b.min_time) ? b.min_time : FLAGS_benchmark_min_time;
Eric Fiselier133a7202017-04-18 07:17:20 +0000339
340 // Determine if this run should be reported; Either it has
341 // run for a sufficient amount of time or because an error was reported.
342 const bool should_report = repetition_num > 0
343 || has_explicit_iteration_count // An exact iteration count was requested
344 || results.has_error_
345 || iters >= kMaxIterations
346 || seconds >= min_time // the elapsed time is large enough
347 // CPU time is specified but the elapsed real time greatly exceeds the
348 // minimum time. Note that user provided timers are except from this
349 // sanity check.
350 || ((results.real_time_used >= 5 * min_time) && !b.use_manual_time);
351
352 if (should_report) {
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000353 BenchmarkReporter::Run report =
354 CreateRunReport(b, results, iters, seconds);
355 if (!report.error_occurred && b.complexity != oNone)
356 complexity_reports->push_back(report);
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000357 reports.push_back(report);
358 break;
359 }
360
361 // See how much iterations should be increased by
362 // Note: Avoid division by zero with max(seconds, 1ns).
363 double multiplier = min_time * 1.4 / std::max(seconds, 1e-9);
364 // If our last run was at least 10% of FLAGS_benchmark_min_time then we
365 // use the multiplier directly. Otherwise we use at most 10 times
366 // expansion.
367 // NOTE: When the last run was at least 10% of the min time the max
368 // expansion should be 14x.
369 bool is_significant = (seconds / min_time) > 0.1;
370 multiplier = is_significant ? multiplier : std::min(10.0, multiplier);
371 if (multiplier <= 1.0) multiplier = 2.0;
372 double next_iters = std::max(multiplier * iters, iters + 1.0);
373 if (next_iters > kMaxIterations) {
374 next_iters = kMaxIterations;
375 }
376 VLOG(3) << "Next iters: " << next_iters << ", " << multiplier << "\n";
377 iters = static_cast<int>(next_iters + 0.5);
378 }
379 }
Eric Fiselier4d5e91d2016-08-29 19:12:01 +0000380 // Calculate additional statistics
381 auto stat_reports = ComputeStats(reports);
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000382 if ((b.complexity != oNone) && b.last_benchmark_instance) {
Eric Fiselier4d5e91d2016-08-29 19:12:01 +0000383 auto additional_run_stats = ComputeBigO(*complexity_reports);
384 stat_reports.insert(stat_reports.end(), additional_run_stats.begin(),
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000385 additional_run_stats.end());
Eric Fiselier4d5e91d2016-08-29 19:12:01 +0000386 complexity_reports->clear();
387 }
Eric Fiselierf6e09e52016-08-09 18:56:48 +0000388
Eric Fiselier4d5e91d2016-08-29 19:12:01 +0000389 if (report_aggregates_only) reports.clear();
390 reports.insert(reports.end(), stat_reports.begin(), stat_reports.end());
Eric Fiselierf6e09e52016-08-09 18:56:48 +0000391 return reports;
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000392}
393
394} // namespace
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000395} // namespace internal
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000396
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000397State::State(size_t max_iters, const std::vector<int>& ranges, int thread_i,
398 int n_threads, internal::ThreadTimer* timer,
399 internal::ThreadManager* manager)
400 : started_(false),
401 finished_(false),
Eric Fiselier19039762018-01-18 04:23:01 +0000402 total_iterations_(max_iters + 1),
Eric Fiselierf6e09e52016-08-09 18:56:48 +0000403 range_(ranges),
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000404 bytes_processed_(0),
405 items_processed_(0),
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000406 complexity_n_(0),
407 error_occurred_(false),
Eric Fiselier133a7202017-04-18 07:17:20 +0000408 counters(),
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000409 thread_index(thread_i),
410 threads(n_threads),
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000411 max_iterations(max_iters),
412 timer_(timer),
413 manager_(manager) {
414 CHECK(max_iterations != 0) << "At least one iteration must be run";
Eric Fiselier19039762018-01-18 04:23:01 +0000415 CHECK(total_iterations_ != 0) << "max iterations wrapped around";
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000416 CHECK_LT(thread_index, threads) << "thread_index must be less than threads";
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000417}
418
419void State::PauseTiming() {
420 // Add in time accumulated so far
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000421 CHECK(started_ && !finished_ && !error_occurred_);
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000422 timer_->StopTimer();
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000423}
424
425void State::ResumeTiming() {
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000426 CHECK(started_ && !finished_ && !error_occurred_);
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000427 timer_->StartTimer();
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000428}
429
430void State::SkipWithError(const char* msg) {
431 CHECK(msg);
432 error_occurred_ = true;
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000433 {
434 MutexLock l(manager_->GetBenchmarkMutex());
435 if (manager_->results.has_error_ == false) {
436 manager_->results.error_message_ = msg;
437 manager_->results.has_error_ = true;
438 }
439 }
Eric Fiselier19039762018-01-18 04:23:01 +0000440 total_iterations_ = 1;
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000441 if (timer_->running()) timer_->StopTimer();
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000442}
443
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000444void State::SetIterationTime(double seconds) {
445 timer_->SetIterationTime(seconds);
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000446}
447
448void State::SetLabel(const char* label) {
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000449 MutexLock l(manager_->GetBenchmarkMutex());
450 manager_->results.report_label_ = label;
451}
452
453void State::StartKeepRunning() {
454 CHECK(!started_ && !finished_);
455 started_ = true;
456 manager_->StartStopBarrier();
457 if (!error_occurred_) ResumeTiming();
458}
459
460void State::FinishKeepRunning() {
461 CHECK(started_ && (!finished_ || error_occurred_));
462 if (!error_occurred_) {
463 PauseTiming();
464 }
Eric Fiselier19039762018-01-18 04:23:01 +0000465 // Total iterations has now wrapped around zero. Fix this.
466 total_iterations_ = 1;
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000467 finished_ = true;
468 manager_->StartStopBarrier();
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000469}
470
471namespace internal {
472namespace {
473
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000474void RunBenchmarks(const std::vector<Benchmark::Instance>& benchmarks,
Eric Fiselierf6e09e52016-08-09 18:56:48 +0000475 BenchmarkReporter* console_reporter,
476 BenchmarkReporter* file_reporter) {
477 // Note the file_reporter can be null.
478 CHECK(console_reporter != nullptr);
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000479
480 // Determine the width of the name field using a minimum width of 10.
481 bool has_repetitions = FLAGS_benchmark_repetitions > 1;
482 size_t name_field_width = 10;
Eric Fiselier19039762018-01-18 04:23:01 +0000483 size_t stat_field_width = 0;
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000484 for (const Benchmark::Instance& benchmark : benchmarks) {
485 name_field_width =
486 std::max<size_t>(name_field_width, benchmark.name.size());
487 has_repetitions |= benchmark.repetitions > 1;
Eric Fiselier19039762018-01-18 04:23:01 +0000488
489 for(const auto& Stat : *benchmark.statistics)
490 stat_field_width = std::max<size_t>(stat_field_width, Stat.name_.size());
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000491 }
Eric Fiselier19039762018-01-18 04:23:01 +0000492 if (has_repetitions) name_field_width += 1 + stat_field_width;
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000493
494 // Print header here
495 BenchmarkReporter::Context context;
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000496 context.name_field_width = name_field_width;
497
498 // Keep track of runing times of all instances of current benchmark
499 std::vector<BenchmarkReporter::Run> complexity_reports;
500
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000501 // We flush streams after invoking reporter methods that write to them. This
502 // ensures users get timely updates even when streams are not line-buffered.
503 auto flushStreams = [](BenchmarkReporter* reporter) {
504 if (!reporter) return;
505 std::flush(reporter->GetOutputStream());
506 std::flush(reporter->GetErrorStream());
507 };
508
509 if (console_reporter->ReportContext(context) &&
510 (!file_reporter || file_reporter->ReportContext(context))) {
511 flushStreams(console_reporter);
512 flushStreams(file_reporter);
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000513 for (const auto& benchmark : benchmarks) {
Eric Fiselierf6e09e52016-08-09 18:56:48 +0000514 std::vector<BenchmarkReporter::Run> reports =
515 RunBenchmark(benchmark, &complexity_reports);
516 console_reporter->ReportRuns(reports);
517 if (file_reporter) file_reporter->ReportRuns(reports);
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000518 flushStreams(console_reporter);
519 flushStreams(file_reporter);
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000520 }
521 }
Eric Fiselierf6e09e52016-08-09 18:56:48 +0000522 console_reporter->Finalize();
523 if (file_reporter) file_reporter->Finalize();
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000524 flushStreams(console_reporter);
525 flushStreams(file_reporter);
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000526}
527
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000528std::unique_ptr<BenchmarkReporter> CreateReporter(
Eric Fiselier19039762018-01-18 04:23:01 +0000529 std::string const& name, ConsoleReporter::OutputOptions output_opts) {
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000530 typedef std::unique_ptr<BenchmarkReporter> PtrType;
Eric Fiselierf6e09e52016-08-09 18:56:48 +0000531 if (name == "console") {
Eric Fiselier19039762018-01-18 04:23:01 +0000532 return PtrType(new ConsoleReporter(output_opts));
Eric Fiselierf6e09e52016-08-09 18:56:48 +0000533 } else if (name == "json") {
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000534 return PtrType(new JSONReporter);
Eric Fiselierf6e09e52016-08-09 18:56:48 +0000535 } else if (name == "csv") {
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000536 return PtrType(new CSVReporter);
537 } else {
Eric Fiselierf6e09e52016-08-09 18:56:48 +0000538 std::cerr << "Unexpected format: '" << name << "'\n";
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000539 std::exit(1);
540 }
541}
542
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000543} // end namespace
Eric Fiselier19039762018-01-18 04:23:01 +0000544
545bool IsZero(double n) {
546 return std::abs(n) < std::numeric_limits<double>::epsilon();
547}
548
549ConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color) {
550 int output_opts = ConsoleReporter::OO_Defaults;
551 if ((FLAGS_benchmark_color == "auto" && IsColorTerminal()) ||
552 IsTruthyFlagValue(FLAGS_benchmark_color)) {
553 output_opts |= ConsoleReporter::OO_Color;
554 } else {
555 output_opts &= ~ConsoleReporter::OO_Color;
556 }
557 if(force_no_color) {
558 output_opts &= ~ConsoleReporter::OO_Color;
559 }
560 if(FLAGS_benchmark_counters_tabular) {
561 output_opts |= ConsoleReporter::OO_Tabular;
562 } else {
563 output_opts &= ~ConsoleReporter::OO_Tabular;
564 }
565 return static_cast< ConsoleReporter::OutputOptions >(output_opts);
566}
567
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000568} // end namespace internal
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000569
570size_t RunSpecifiedBenchmarks() {
Eric Fiselierf6e09e52016-08-09 18:56:48 +0000571 return RunSpecifiedBenchmarks(nullptr, nullptr);
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000572}
573
Eric Fiselierf6e09e52016-08-09 18:56:48 +0000574size_t RunSpecifiedBenchmarks(BenchmarkReporter* console_reporter) {
575 return RunSpecifiedBenchmarks(console_reporter, nullptr);
576}
577
Eric Fiselierf6e09e52016-08-09 18:56:48 +0000578size_t RunSpecifiedBenchmarks(BenchmarkReporter* console_reporter,
579 BenchmarkReporter* file_reporter) {
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000580 std::string spec = FLAGS_benchmark_filter;
581 if (spec.empty() || spec == "all")
582 spec = "."; // Regexp that matches all benchmarks
583
Eric Fiselier4d5e91d2016-08-29 19:12:01 +0000584 // Setup the reporters
585 std::ofstream output_file;
586 std::unique_ptr<BenchmarkReporter> default_console_reporter;
587 std::unique_ptr<BenchmarkReporter> default_file_reporter;
588 if (!console_reporter) {
Eric Fiselier19039762018-01-18 04:23:01 +0000589 default_console_reporter = internal::CreateReporter(
590 FLAGS_benchmark_format, internal::GetOutputOptions());
Eric Fiselier4d5e91d2016-08-29 19:12:01 +0000591 console_reporter = default_console_reporter.get();
592 }
593 auto& Out = console_reporter->GetOutputStream();
594 auto& Err = console_reporter->GetErrorStream();
595
596 std::string const& fname = FLAGS_benchmark_out;
Eric Fiselier19039762018-01-18 04:23:01 +0000597 if (fname.empty() && file_reporter) {
Eric Fiselier4d5e91d2016-08-29 19:12:01 +0000598 Err << "A custom file reporter was provided but "
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000599 "--benchmark_out=<file> was not specified."
600 << std::endl;
Eric Fiselier4d5e91d2016-08-29 19:12:01 +0000601 std::exit(1);
602 }
Eric Fiselier19039762018-01-18 04:23:01 +0000603 if (!fname.empty()) {
Eric Fiselier4d5e91d2016-08-29 19:12:01 +0000604 output_file.open(fname);
605 if (!output_file.is_open()) {
606 Err << "invalid file name: '" << fname << std::endl;
607 std::exit(1);
608 }
609 if (!file_reporter) {
610 default_file_reporter = internal::CreateReporter(
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000611 FLAGS_benchmark_out_format, ConsoleReporter::OO_None);
Eric Fiselier4d5e91d2016-08-29 19:12:01 +0000612 file_reporter = default_file_reporter.get();
613 }
614 file_reporter->SetOutputStream(&output_file);
615 file_reporter->SetErrorStream(&output_file);
616 }
617
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000618 std::vector<internal::Benchmark::Instance> benchmarks;
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000619 if (!FindBenchmarksInternal(spec, &benchmarks, &Err)) return 0;
620
621 if (benchmarks.empty()) {
622 Err << "Failed to match any benchmarks against regex: " << spec << "\n";
623 return 0;
624 }
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000625
626 if (FLAGS_benchmark_list_tests) {
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000627 for (auto const& benchmark : benchmarks) Out << benchmark.name << "\n";
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000628 } else {
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000629 internal::RunBenchmarks(benchmarks, console_reporter, file_reporter);
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000630 }
Eric Fiselier4d5e91d2016-08-29 19:12:01 +0000631
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000632 return benchmarks.size();
633}
634
635namespace internal {
636
637void PrintUsageAndExit() {
638 fprintf(stdout,
639 "benchmark"
640 " [--benchmark_list_tests={true|false}]\n"
641 " [--benchmark_filter=<regex>]\n"
642 " [--benchmark_min_time=<min_time>]\n"
643 " [--benchmark_repetitions=<num_repetitions>]\n"
Eric Fiselier4d5e91d2016-08-29 19:12:01 +0000644 " [--benchmark_report_aggregates_only={true|false}\n"
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000645 " [--benchmark_format=<console|json|csv>]\n"
Eric Fiselierf6e09e52016-08-09 18:56:48 +0000646 " [--benchmark_out=<filename>]\n"
647 " [--benchmark_out_format=<json|console|csv>]\n"
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000648 " [--benchmark_color={auto|true|false}]\n"
Eric Fiselier19039762018-01-18 04:23:01 +0000649 " [--benchmark_counters_tabular={true|false}]\n"
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000650 " [--v=<verbosity>]\n");
651 exit(0);
652}
653
654void ParseCommandLineFlags(int* argc, char** argv) {
655 using namespace benchmark;
656 for (int i = 1; i < *argc; ++i) {
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000657 if (ParseBoolFlag(argv[i], "benchmark_list_tests",
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000658 &FLAGS_benchmark_list_tests) ||
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000659 ParseStringFlag(argv[i], "benchmark_filter", &FLAGS_benchmark_filter) ||
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000660 ParseDoubleFlag(argv[i], "benchmark_min_time",
661 &FLAGS_benchmark_min_time) ||
662 ParseInt32Flag(argv[i], "benchmark_repetitions",
663 &FLAGS_benchmark_repetitions) ||
Eric Fiselier4d5e91d2016-08-29 19:12:01 +0000664 ParseBoolFlag(argv[i], "benchmark_report_aggregates_only",
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000665 &FLAGS_benchmark_report_aggregates_only) ||
666 ParseStringFlag(argv[i], "benchmark_format", &FLAGS_benchmark_format) ||
667 ParseStringFlag(argv[i], "benchmark_out", &FLAGS_benchmark_out) ||
Eric Fiselierf6e09e52016-08-09 18:56:48 +0000668 ParseStringFlag(argv[i], "benchmark_out_format",
669 &FLAGS_benchmark_out_format) ||
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000670 ParseStringFlag(argv[i], "benchmark_color", &FLAGS_benchmark_color) ||
671 // "color_print" is the deprecated name for "benchmark_color".
672 // TODO: Remove this.
673 ParseStringFlag(argv[i], "color_print", &FLAGS_benchmark_color) ||
Eric Fiselier19039762018-01-18 04:23:01 +0000674 ParseBoolFlag(argv[i], "benchmark_counters_tabular",
675 &FLAGS_benchmark_counters_tabular) ||
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000676 ParseInt32Flag(argv[i], "v", &FLAGS_v)) {
Eric Fiselier133a7202017-04-18 07:17:20 +0000677 for (int j = i; j != *argc - 1; ++j) argv[j] = argv[j + 1];
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000678
679 --(*argc);
680 --i;
681 } else if (IsFlag(argv[i], "help")) {
682 PrintUsageAndExit();
683 }
684 }
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000685 for (auto const* flag :
686 {&FLAGS_benchmark_format, &FLAGS_benchmark_out_format})
687 if (*flag != "console" && *flag != "json" && *flag != "csv") {
688 PrintUsageAndExit();
689 }
690 if (FLAGS_benchmark_color.empty()) {
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000691 PrintUsageAndExit();
692 }
693}
694
Eric Fiselier4d5e91d2016-08-29 19:12:01 +0000695int InitializeStreams() {
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000696 static std::ios_base::Init init;
697 return 0;
Eric Fiselier4d5e91d2016-08-29 19:12:01 +0000698}
699
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000700} // end namespace internal
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000701
702void Initialize(int* argc, char** argv) {
703 internal::ParseCommandLineFlags(argc, argv);
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000704 internal::LogLevel() = FLAGS_v;
Eric Fiselierb08d8b12016-07-19 23:07:03 +0000705}
706
Eric Fiselier133a7202017-04-18 07:17:20 +0000707bool ReportUnrecognizedArguments(int argc, char** argv) {
708 for (int i = 1; i < argc; ++i) {
709 fprintf(stderr, "%s: error: unrecognized command-line flag: %s\n", argv[0], argv[i]);
710 }
711 return argc > 1;
712}
713
Eric Fiselierfbc9ff22016-11-05 00:30:27 +0000714} // end namespace benchmark