1*06f32e7eSjoerg // Copyright 2015 Google Inc. All rights reserved.
2*06f32e7eSjoerg //
3*06f32e7eSjoerg // Licensed under the Apache License, Version 2.0 (the "License");
4*06f32e7eSjoerg // you may not use this file except in compliance with the License.
5*06f32e7eSjoerg // You may obtain a copy of the License at
6*06f32e7eSjoerg //
7*06f32e7eSjoerg //     http://www.apache.org/licenses/LICENSE-2.0
8*06f32e7eSjoerg //
9*06f32e7eSjoerg // Unless required by applicable law or agreed to in writing, software
10*06f32e7eSjoerg // distributed under the License is distributed on an "AS IS" BASIS,
11*06f32e7eSjoerg // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12*06f32e7eSjoerg // See the License for the specific language governing permissions and
13*06f32e7eSjoerg // limitations under the License.
14*06f32e7eSjoerg 
15*06f32e7eSjoerg #include "benchmark/benchmark.h"
16*06f32e7eSjoerg #include "benchmark_api_internal.h"
17*06f32e7eSjoerg #include "internal_macros.h"
18*06f32e7eSjoerg 
19*06f32e7eSjoerg #ifndef BENCHMARK_OS_WINDOWS
20*06f32e7eSjoerg #ifndef BENCHMARK_OS_FUCHSIA
21*06f32e7eSjoerg #include <sys/resource.h>
22*06f32e7eSjoerg #endif
23*06f32e7eSjoerg #include <sys/time.h>
24*06f32e7eSjoerg #include <unistd.h>
25*06f32e7eSjoerg #endif
26*06f32e7eSjoerg 
27*06f32e7eSjoerg #include <algorithm>
28*06f32e7eSjoerg #include <atomic>
29*06f32e7eSjoerg #include <condition_variable>
30*06f32e7eSjoerg #include <cstdio>
31*06f32e7eSjoerg #include <cstdlib>
32*06f32e7eSjoerg #include <fstream>
33*06f32e7eSjoerg #include <iostream>
34*06f32e7eSjoerg #include <memory>
35*06f32e7eSjoerg #include <string>
36*06f32e7eSjoerg #include <thread>
37*06f32e7eSjoerg 
38*06f32e7eSjoerg #include "check.h"
39*06f32e7eSjoerg #include "colorprint.h"
40*06f32e7eSjoerg #include "commandlineflags.h"
41*06f32e7eSjoerg #include "complexity.h"
42*06f32e7eSjoerg #include "counter.h"
43*06f32e7eSjoerg #include "internal_macros.h"
44*06f32e7eSjoerg #include "log.h"
45*06f32e7eSjoerg #include "mutex.h"
46*06f32e7eSjoerg #include "re.h"
47*06f32e7eSjoerg #include "statistics.h"
48*06f32e7eSjoerg #include "string_util.h"
49*06f32e7eSjoerg #include "thread_manager.h"
50*06f32e7eSjoerg #include "thread_timer.h"
51*06f32e7eSjoerg 
52*06f32e7eSjoerg DEFINE_bool(benchmark_list_tests, false,
53*06f32e7eSjoerg             "Print a list of benchmarks. This option overrides all other "
54*06f32e7eSjoerg             "options.");
55*06f32e7eSjoerg 
56*06f32e7eSjoerg DEFINE_string(benchmark_filter, ".",
57*06f32e7eSjoerg               "A regular expression that specifies the set of benchmarks "
58*06f32e7eSjoerg               "to execute.  If this flag is empty, no benchmarks are run.  "
59*06f32e7eSjoerg               "If this flag is the string \"all\", all benchmarks linked "
60*06f32e7eSjoerg               "into the process are run.");
61*06f32e7eSjoerg 
62*06f32e7eSjoerg DEFINE_double(benchmark_min_time, 0.5,
63*06f32e7eSjoerg               "Minimum number of seconds we should run benchmark before "
64*06f32e7eSjoerg               "results are considered significant.  For cpu-time based "
65*06f32e7eSjoerg               "tests, this is the lower bound on the total cpu time "
66*06f32e7eSjoerg               "used by all threads that make up the test.  For real-time "
67*06f32e7eSjoerg               "based tests, this is the lower bound on the elapsed time "
68*06f32e7eSjoerg               "of the benchmark execution, regardless of number of "
69*06f32e7eSjoerg               "threads.");
70*06f32e7eSjoerg 
71*06f32e7eSjoerg DEFINE_int32(benchmark_repetitions, 1,
72*06f32e7eSjoerg              "The number of runs of each benchmark. If greater than 1, the "
73*06f32e7eSjoerg              "mean and standard deviation of the runs will be reported.");
74*06f32e7eSjoerg 
75*06f32e7eSjoerg DEFINE_bool(benchmark_report_aggregates_only, false,
76*06f32e7eSjoerg             "Report the result of each benchmark repetitions. When 'true' is "
77*06f32e7eSjoerg             "specified only the mean, standard deviation, and other statistics "
78*06f32e7eSjoerg             "are reported for repeated benchmarks.");
79*06f32e7eSjoerg 
80*06f32e7eSjoerg DEFINE_string(benchmark_format, "console",
81*06f32e7eSjoerg               "The format to use for console output. Valid values are "
82*06f32e7eSjoerg               "'console', 'json', or 'csv'.");
83*06f32e7eSjoerg 
84*06f32e7eSjoerg DEFINE_string(benchmark_out_format, "json",
85*06f32e7eSjoerg               "The format to use for file output. Valid values are "
86*06f32e7eSjoerg               "'console', 'json', or 'csv'.");
87*06f32e7eSjoerg 
88*06f32e7eSjoerg DEFINE_string(benchmark_out, "", "The file to write additional output to");
89*06f32e7eSjoerg 
90*06f32e7eSjoerg DEFINE_string(benchmark_color, "auto",
91*06f32e7eSjoerg               "Whether to use colors in the output.  Valid values: "
92*06f32e7eSjoerg               "'true'/'yes'/1, 'false'/'no'/0, and 'auto'. 'auto' means to use "
93*06f32e7eSjoerg               "colors if the output is being sent to a terminal and the TERM "
94*06f32e7eSjoerg               "environment variable is set to a terminal type that supports "
95*06f32e7eSjoerg               "colors.");
96*06f32e7eSjoerg 
97*06f32e7eSjoerg DEFINE_bool(benchmark_counters_tabular, false,
98*06f32e7eSjoerg             "Whether to use tabular format when printing user counters to "
99*06f32e7eSjoerg             "the console.  Valid values: 'true'/'yes'/1, 'false'/'no'/0."
100*06f32e7eSjoerg             "Defaults to false.");
101*06f32e7eSjoerg 
102*06f32e7eSjoerg DEFINE_int32(v, 0, "The level of verbose logging to output");
103*06f32e7eSjoerg 
104*06f32e7eSjoerg namespace benchmark {
105*06f32e7eSjoerg 
106*06f32e7eSjoerg namespace {
107*06f32e7eSjoerg static const size_t kMaxIterations = 1000000000;
108*06f32e7eSjoerg }  // end namespace
109*06f32e7eSjoerg 
110*06f32e7eSjoerg namespace internal {
111*06f32e7eSjoerg 
UseCharPointer(char const volatile *)112*06f32e7eSjoerg void UseCharPointer(char const volatile*) {}
113*06f32e7eSjoerg 
114*06f32e7eSjoerg namespace {
115*06f32e7eSjoerg 
CreateRunReport(const benchmark::internal::Benchmark::Instance & b,const internal::ThreadManager::Result & results,double seconds)116*06f32e7eSjoerg BenchmarkReporter::Run CreateRunReport(
117*06f32e7eSjoerg     const benchmark::internal::Benchmark::Instance& b,
118*06f32e7eSjoerg     const internal::ThreadManager::Result& results,
119*06f32e7eSjoerg     double seconds) {
120*06f32e7eSjoerg   // Create report about this benchmark run.
121*06f32e7eSjoerg   BenchmarkReporter::Run report;
122*06f32e7eSjoerg 
123*06f32e7eSjoerg   report.benchmark_name = b.name;
124*06f32e7eSjoerg   report.error_occurred = results.has_error_;
125*06f32e7eSjoerg   report.error_message = results.error_message_;
126*06f32e7eSjoerg   report.report_label = results.report_label_;
127*06f32e7eSjoerg   // This is the total iterations across all threads.
128*06f32e7eSjoerg   report.iterations = results.iterations;
129*06f32e7eSjoerg   report.time_unit = b.time_unit;
130*06f32e7eSjoerg 
131*06f32e7eSjoerg   if (!report.error_occurred) {
132*06f32e7eSjoerg     double bytes_per_second = 0;
133*06f32e7eSjoerg     if (results.bytes_processed > 0 && seconds > 0.0) {
134*06f32e7eSjoerg       bytes_per_second = (results.bytes_processed / seconds);
135*06f32e7eSjoerg     }
136*06f32e7eSjoerg     double items_per_second = 0;
137*06f32e7eSjoerg     if (results.items_processed > 0 && seconds > 0.0) {
138*06f32e7eSjoerg       items_per_second = (results.items_processed / seconds);
139*06f32e7eSjoerg     }
140*06f32e7eSjoerg 
141*06f32e7eSjoerg     if (b.use_manual_time) {
142*06f32e7eSjoerg       report.real_accumulated_time = results.manual_time_used;
143*06f32e7eSjoerg     } else {
144*06f32e7eSjoerg       report.real_accumulated_time = results.real_time_used;
145*06f32e7eSjoerg     }
146*06f32e7eSjoerg     report.cpu_accumulated_time = results.cpu_time_used;
147*06f32e7eSjoerg     report.bytes_per_second = bytes_per_second;
148*06f32e7eSjoerg     report.items_per_second = items_per_second;
149*06f32e7eSjoerg     report.complexity_n = results.complexity_n;
150*06f32e7eSjoerg     report.complexity = b.complexity;
151*06f32e7eSjoerg     report.complexity_lambda = b.complexity_lambda;
152*06f32e7eSjoerg     report.statistics = b.statistics;
153*06f32e7eSjoerg     report.counters = results.counters;
154*06f32e7eSjoerg     internal::Finish(&report.counters, seconds, b.threads);
155*06f32e7eSjoerg   }
156*06f32e7eSjoerg   return report;
157*06f32e7eSjoerg }
158*06f32e7eSjoerg 
159*06f32e7eSjoerg // Execute one thread of benchmark b for the specified number of iterations.
160*06f32e7eSjoerg // Adds the stats collected for the thread into *total.
RunInThread(const benchmark::internal::Benchmark::Instance * b,size_t iters,int thread_id,internal::ThreadManager * manager)161*06f32e7eSjoerg void RunInThread(const benchmark::internal::Benchmark::Instance* b,
162*06f32e7eSjoerg                  size_t iters, int thread_id,
163*06f32e7eSjoerg                  internal::ThreadManager* manager) {
164*06f32e7eSjoerg   internal::ThreadTimer timer;
165*06f32e7eSjoerg   State st(iters, b->arg, thread_id, b->threads, &timer, manager);
166*06f32e7eSjoerg   b->benchmark->Run(st);
167*06f32e7eSjoerg   CHECK(st.iterations() >= st.max_iterations)
168*06f32e7eSjoerg       << "Benchmark returned before State::KeepRunning() returned false!";
169*06f32e7eSjoerg   {
170*06f32e7eSjoerg     MutexLock l(manager->GetBenchmarkMutex());
171*06f32e7eSjoerg     internal::ThreadManager::Result& results = manager->results;
172*06f32e7eSjoerg     results.iterations += st.iterations();
173*06f32e7eSjoerg     results.cpu_time_used += timer.cpu_time_used();
174*06f32e7eSjoerg     results.real_time_used += timer.real_time_used();
175*06f32e7eSjoerg     results.manual_time_used += timer.manual_time_used();
176*06f32e7eSjoerg     results.bytes_processed += st.bytes_processed();
177*06f32e7eSjoerg     results.items_processed += st.items_processed();
178*06f32e7eSjoerg     results.complexity_n += st.complexity_length_n();
179*06f32e7eSjoerg     internal::Increment(&results.counters, st.counters);
180*06f32e7eSjoerg   }
181*06f32e7eSjoerg   manager->NotifyThreadComplete();
182*06f32e7eSjoerg }
183*06f32e7eSjoerg 
RunBenchmark(const benchmark::internal::Benchmark::Instance & b,std::vector<BenchmarkReporter::Run> * complexity_reports)184*06f32e7eSjoerg std::vector<BenchmarkReporter::Run> RunBenchmark(
185*06f32e7eSjoerg     const benchmark::internal::Benchmark::Instance& b,
186*06f32e7eSjoerg     std::vector<BenchmarkReporter::Run>* complexity_reports) {
187*06f32e7eSjoerg   std::vector<BenchmarkReporter::Run> reports;  // return value
188*06f32e7eSjoerg 
189*06f32e7eSjoerg   const bool has_explicit_iteration_count = b.iterations != 0;
190*06f32e7eSjoerg   size_t iters = has_explicit_iteration_count ? b.iterations : 1;
191*06f32e7eSjoerg   std::unique_ptr<internal::ThreadManager> manager;
192*06f32e7eSjoerg   std::vector<std::thread> pool(b.threads - 1);
193*06f32e7eSjoerg   const int repeats =
194*06f32e7eSjoerg       b.repetitions != 0 ? b.repetitions : FLAGS_benchmark_repetitions;
195*06f32e7eSjoerg   const bool report_aggregates_only =
196*06f32e7eSjoerg       repeats != 1 &&
197*06f32e7eSjoerg       (b.report_mode == internal::RM_Unspecified
198*06f32e7eSjoerg            ? FLAGS_benchmark_report_aggregates_only
199*06f32e7eSjoerg            : b.report_mode == internal::RM_ReportAggregatesOnly);
200*06f32e7eSjoerg   for (int repetition_num = 0; repetition_num < repeats; repetition_num++) {
201*06f32e7eSjoerg     for (;;) {
202*06f32e7eSjoerg       // Try benchmark
203*06f32e7eSjoerg       VLOG(2) << "Running " << b.name << " for " << iters << "\n";
204*06f32e7eSjoerg 
205*06f32e7eSjoerg       manager.reset(new internal::ThreadManager(b.threads));
206*06f32e7eSjoerg       for (std::size_t ti = 0; ti < pool.size(); ++ti) {
207*06f32e7eSjoerg         pool[ti] = std::thread(&RunInThread, &b, iters,
208*06f32e7eSjoerg                                static_cast<int>(ti + 1), manager.get());
209*06f32e7eSjoerg       }
210*06f32e7eSjoerg       RunInThread(&b, iters, 0, manager.get());
211*06f32e7eSjoerg       manager->WaitForAllThreads();
212*06f32e7eSjoerg       for (std::thread& thread : pool) thread.join();
213*06f32e7eSjoerg       internal::ThreadManager::Result results;
214*06f32e7eSjoerg       {
215*06f32e7eSjoerg         MutexLock l(manager->GetBenchmarkMutex());
216*06f32e7eSjoerg         results = manager->results;
217*06f32e7eSjoerg       }
218*06f32e7eSjoerg       manager.reset();
219*06f32e7eSjoerg       // Adjust real/manual time stats since they were reported per thread.
220*06f32e7eSjoerg       results.real_time_used /= b.threads;
221*06f32e7eSjoerg       results.manual_time_used /= b.threads;
222*06f32e7eSjoerg 
223*06f32e7eSjoerg       VLOG(2) << "Ran in " << results.cpu_time_used << "/"
224*06f32e7eSjoerg               << results.real_time_used << "\n";
225*06f32e7eSjoerg 
226*06f32e7eSjoerg       // Base decisions off of real time if requested by this benchmark.
227*06f32e7eSjoerg       double seconds = results.cpu_time_used;
228*06f32e7eSjoerg       if (b.use_manual_time) {
229*06f32e7eSjoerg         seconds = results.manual_time_used;
230*06f32e7eSjoerg       } else if (b.use_real_time) {
231*06f32e7eSjoerg         seconds = results.real_time_used;
232*06f32e7eSjoerg       }
233*06f32e7eSjoerg 
234*06f32e7eSjoerg       const double min_time =
235*06f32e7eSjoerg           !IsZero(b.min_time) ? b.min_time : FLAGS_benchmark_min_time;
236*06f32e7eSjoerg 
237*06f32e7eSjoerg       // Determine if this run should be reported; Either it has
238*06f32e7eSjoerg       // run for a sufficient amount of time or because an error was reported.
239*06f32e7eSjoerg       const bool should_report =  repetition_num > 0
240*06f32e7eSjoerg         || has_explicit_iteration_count  // An exact iteration count was requested
241*06f32e7eSjoerg         || results.has_error_
242*06f32e7eSjoerg         || iters >= kMaxIterations  // No chance to try again, we hit the limit.
243*06f32e7eSjoerg         || seconds >= min_time  // the elapsed time is large enough
244*06f32e7eSjoerg         // CPU time is specified but the elapsed real time greatly exceeds the
245*06f32e7eSjoerg         // minimum time. Note that user provided timers are except from this
246*06f32e7eSjoerg         // sanity check.
247*06f32e7eSjoerg         || ((results.real_time_used >= 5 * min_time) && !b.use_manual_time);
248*06f32e7eSjoerg 
249*06f32e7eSjoerg       if (should_report) {
250*06f32e7eSjoerg         BenchmarkReporter::Run report = CreateRunReport(b, results, seconds);
251*06f32e7eSjoerg         if (!report.error_occurred && b.complexity != oNone)
252*06f32e7eSjoerg           complexity_reports->push_back(report);
253*06f32e7eSjoerg         reports.push_back(report);
254*06f32e7eSjoerg         break;
255*06f32e7eSjoerg       }
256*06f32e7eSjoerg 
257*06f32e7eSjoerg       // See how much iterations should be increased by
258*06f32e7eSjoerg       // Note: Avoid division by zero with max(seconds, 1ns).
259*06f32e7eSjoerg       double multiplier = min_time * 1.4 / std::max(seconds, 1e-9);
260*06f32e7eSjoerg       // If our last run was at least 10% of FLAGS_benchmark_min_time then we
261*06f32e7eSjoerg       // use the multiplier directly. Otherwise we use at most 10 times
262*06f32e7eSjoerg       // expansion.
263*06f32e7eSjoerg       // NOTE: When the last run was at least 10% of the min time the max
264*06f32e7eSjoerg       // expansion should be 14x.
265*06f32e7eSjoerg       bool is_significant = (seconds / min_time) > 0.1;
266*06f32e7eSjoerg       multiplier = is_significant ? multiplier : std::min(10.0, multiplier);
267*06f32e7eSjoerg       if (multiplier <= 1.0) multiplier = 2.0;
268*06f32e7eSjoerg       double next_iters = std::max(multiplier * iters, iters + 1.0);
269*06f32e7eSjoerg       if (next_iters > kMaxIterations) {
270*06f32e7eSjoerg         next_iters = kMaxIterations;
271*06f32e7eSjoerg       }
272*06f32e7eSjoerg       VLOG(3) << "Next iters: " << next_iters << ", " << multiplier << "\n";
273*06f32e7eSjoerg       iters = static_cast<int>(next_iters + 0.5);
274*06f32e7eSjoerg     }
275*06f32e7eSjoerg   }
276*06f32e7eSjoerg   // Calculate additional statistics
277*06f32e7eSjoerg   auto stat_reports = ComputeStats(reports);
278*06f32e7eSjoerg   if ((b.complexity != oNone) && b.last_benchmark_instance) {
279*06f32e7eSjoerg     auto additional_run_stats = ComputeBigO(*complexity_reports);
280*06f32e7eSjoerg     stat_reports.insert(stat_reports.end(), additional_run_stats.begin(),
281*06f32e7eSjoerg                         additional_run_stats.end());
282*06f32e7eSjoerg     complexity_reports->clear();
283*06f32e7eSjoerg   }
284*06f32e7eSjoerg 
285*06f32e7eSjoerg   if (report_aggregates_only) reports.clear();
286*06f32e7eSjoerg   reports.insert(reports.end(), stat_reports.begin(), stat_reports.end());
287*06f32e7eSjoerg   return reports;
288*06f32e7eSjoerg }
289*06f32e7eSjoerg 
290*06f32e7eSjoerg }  // namespace
291*06f32e7eSjoerg }  // namespace internal
292*06f32e7eSjoerg 
State(size_t max_iters,const std::vector<int64_t> & ranges,int thread_i,int n_threads,internal::ThreadTimer * timer,internal::ThreadManager * manager)293*06f32e7eSjoerg State::State(size_t max_iters, const std::vector<int64_t>& ranges, int thread_i,
294*06f32e7eSjoerg              int n_threads, internal::ThreadTimer* timer,
295*06f32e7eSjoerg              internal::ThreadManager* manager)
296*06f32e7eSjoerg     : total_iterations_(0),
297*06f32e7eSjoerg       batch_leftover_(0),
298*06f32e7eSjoerg       max_iterations(max_iters),
299*06f32e7eSjoerg       started_(false),
300*06f32e7eSjoerg       finished_(false),
301*06f32e7eSjoerg       error_occurred_(false),
302*06f32e7eSjoerg       range_(ranges),
303*06f32e7eSjoerg       bytes_processed_(0),
304*06f32e7eSjoerg       items_processed_(0),
305*06f32e7eSjoerg       complexity_n_(0),
306*06f32e7eSjoerg       counters(),
307*06f32e7eSjoerg       thread_index(thread_i),
308*06f32e7eSjoerg       threads(n_threads),
309*06f32e7eSjoerg       timer_(timer),
310*06f32e7eSjoerg       manager_(manager) {
311*06f32e7eSjoerg   CHECK(max_iterations != 0) << "At least one iteration must be run";
312*06f32e7eSjoerg   CHECK_LT(thread_index, threads) << "thread_index must be less than threads";
313*06f32e7eSjoerg 
314*06f32e7eSjoerg   // Note: The use of offsetof below is technically undefined until C++17
315*06f32e7eSjoerg   // because State is not a standard layout type. However, all compilers
316*06f32e7eSjoerg   // currently provide well-defined behavior as an extension (which is
317*06f32e7eSjoerg   // demonstrated since constexpr evaluation must diagnose all undefined
318*06f32e7eSjoerg   // behavior). However, GCC and Clang also warn about this use of offsetof,
319*06f32e7eSjoerg   // which must be suppressed.
320*06f32e7eSjoerg #ifdef __GNUC__
321*06f32e7eSjoerg #pragma GCC diagnostic push
322*06f32e7eSjoerg #pragma GCC diagnostic ignored "-Winvalid-offsetof"
323*06f32e7eSjoerg #endif
324*06f32e7eSjoerg   // Offset tests to ensure commonly accessed data is on the first cache line.
325*06f32e7eSjoerg   const int cache_line_size = 64;
326*06f32e7eSjoerg   static_assert(offsetof(State, error_occurred_) <=
327*06f32e7eSjoerg                 (cache_line_size - sizeof(error_occurred_)), "");
328*06f32e7eSjoerg #ifdef __GNUC__
329*06f32e7eSjoerg #pragma GCC diagnostic pop
330*06f32e7eSjoerg #endif
331*06f32e7eSjoerg }
332*06f32e7eSjoerg 
PauseTiming()333*06f32e7eSjoerg void State::PauseTiming() {
334*06f32e7eSjoerg   // Add in time accumulated so far
335*06f32e7eSjoerg   CHECK(started_ && !finished_ && !error_occurred_);
336*06f32e7eSjoerg   timer_->StopTimer();
337*06f32e7eSjoerg }
338*06f32e7eSjoerg 
ResumeTiming()339*06f32e7eSjoerg void State::ResumeTiming() {
340*06f32e7eSjoerg   CHECK(started_ && !finished_ && !error_occurred_);
341*06f32e7eSjoerg   timer_->StartTimer();
342*06f32e7eSjoerg }
343*06f32e7eSjoerg 
SkipWithError(const char * msg)344*06f32e7eSjoerg void State::SkipWithError(const char* msg) {
345*06f32e7eSjoerg   CHECK(msg);
346*06f32e7eSjoerg   error_occurred_ = true;
347*06f32e7eSjoerg   {
348*06f32e7eSjoerg     MutexLock l(manager_->GetBenchmarkMutex());
349*06f32e7eSjoerg     if (manager_->results.has_error_ == false) {
350*06f32e7eSjoerg       manager_->results.error_message_ = msg;
351*06f32e7eSjoerg       manager_->results.has_error_ = true;
352*06f32e7eSjoerg     }
353*06f32e7eSjoerg   }
354*06f32e7eSjoerg   total_iterations_ = 0;
355*06f32e7eSjoerg   if (timer_->running()) timer_->StopTimer();
356*06f32e7eSjoerg }
357*06f32e7eSjoerg 
SetIterationTime(double seconds)358*06f32e7eSjoerg void State::SetIterationTime(double seconds) {
359*06f32e7eSjoerg   timer_->SetIterationTime(seconds);
360*06f32e7eSjoerg }
361*06f32e7eSjoerg 
SetLabel(const char * label)362*06f32e7eSjoerg void State::SetLabel(const char* label) {
363*06f32e7eSjoerg   MutexLock l(manager_->GetBenchmarkMutex());
364*06f32e7eSjoerg   manager_->results.report_label_ = label;
365*06f32e7eSjoerg }
366*06f32e7eSjoerg 
StartKeepRunning()367*06f32e7eSjoerg void State::StartKeepRunning() {
368*06f32e7eSjoerg   CHECK(!started_ && !finished_);
369*06f32e7eSjoerg   started_ = true;
370*06f32e7eSjoerg   total_iterations_ = error_occurred_ ? 0 : max_iterations;
371*06f32e7eSjoerg   manager_->StartStopBarrier();
372*06f32e7eSjoerg   if (!error_occurred_) ResumeTiming();
373*06f32e7eSjoerg }
374*06f32e7eSjoerg 
FinishKeepRunning()375*06f32e7eSjoerg void State::FinishKeepRunning() {
376*06f32e7eSjoerg   CHECK(started_ && (!finished_ || error_occurred_));
377*06f32e7eSjoerg   if (!error_occurred_) {
378*06f32e7eSjoerg     PauseTiming();
379*06f32e7eSjoerg   }
380*06f32e7eSjoerg   // Total iterations has now wrapped around past 0. Fix this.
381*06f32e7eSjoerg   total_iterations_ = 0;
382*06f32e7eSjoerg   finished_ = true;
383*06f32e7eSjoerg   manager_->StartStopBarrier();
384*06f32e7eSjoerg }
385*06f32e7eSjoerg 
386*06f32e7eSjoerg namespace internal {
387*06f32e7eSjoerg namespace {
388*06f32e7eSjoerg 
RunBenchmarks(const std::vector<Benchmark::Instance> & benchmarks,BenchmarkReporter * console_reporter,BenchmarkReporter * file_reporter)389*06f32e7eSjoerg void RunBenchmarks(const std::vector<Benchmark::Instance>& benchmarks,
390*06f32e7eSjoerg                            BenchmarkReporter* console_reporter,
391*06f32e7eSjoerg                            BenchmarkReporter* file_reporter) {
392*06f32e7eSjoerg   // Note the file_reporter can be null.
393*06f32e7eSjoerg   CHECK(console_reporter != nullptr);
394*06f32e7eSjoerg 
395*06f32e7eSjoerg   // Determine the width of the name field using a minimum width of 10.
396*06f32e7eSjoerg   bool has_repetitions = FLAGS_benchmark_repetitions > 1;
397*06f32e7eSjoerg   size_t name_field_width = 10;
398*06f32e7eSjoerg   size_t stat_field_width = 0;
399*06f32e7eSjoerg   for (const Benchmark::Instance& benchmark : benchmarks) {
400*06f32e7eSjoerg     name_field_width =
401*06f32e7eSjoerg         std::max<size_t>(name_field_width, benchmark.name.size());
402*06f32e7eSjoerg     has_repetitions |= benchmark.repetitions > 1;
403*06f32e7eSjoerg 
404*06f32e7eSjoerg     for(const auto& Stat : *benchmark.statistics)
405*06f32e7eSjoerg       stat_field_width = std::max<size_t>(stat_field_width, Stat.name_.size());
406*06f32e7eSjoerg   }
407*06f32e7eSjoerg   if (has_repetitions) name_field_width += 1 + stat_field_width;
408*06f32e7eSjoerg 
409*06f32e7eSjoerg   // Print header here
410*06f32e7eSjoerg   BenchmarkReporter::Context context;
411*06f32e7eSjoerg   context.name_field_width = name_field_width;
412*06f32e7eSjoerg 
413*06f32e7eSjoerg   // Keep track of running times of all instances of current benchmark
414*06f32e7eSjoerg   std::vector<BenchmarkReporter::Run> complexity_reports;
415*06f32e7eSjoerg 
416*06f32e7eSjoerg   // We flush streams after invoking reporter methods that write to them. This
417*06f32e7eSjoerg   // ensures users get timely updates even when streams are not line-buffered.
418*06f32e7eSjoerg   auto flushStreams = [](BenchmarkReporter* reporter) {
419*06f32e7eSjoerg     if (!reporter) return;
420*06f32e7eSjoerg     std::flush(reporter->GetOutputStream());
421*06f32e7eSjoerg     std::flush(reporter->GetErrorStream());
422*06f32e7eSjoerg   };
423*06f32e7eSjoerg 
424*06f32e7eSjoerg   if (console_reporter->ReportContext(context) &&
425*06f32e7eSjoerg       (!file_reporter || file_reporter->ReportContext(context))) {
426*06f32e7eSjoerg     flushStreams(console_reporter);
427*06f32e7eSjoerg     flushStreams(file_reporter);
428*06f32e7eSjoerg     for (const auto& benchmark : benchmarks) {
429*06f32e7eSjoerg       std::vector<BenchmarkReporter::Run> reports =
430*06f32e7eSjoerg           RunBenchmark(benchmark, &complexity_reports);
431*06f32e7eSjoerg       console_reporter->ReportRuns(reports);
432*06f32e7eSjoerg       if (file_reporter) file_reporter->ReportRuns(reports);
433*06f32e7eSjoerg       flushStreams(console_reporter);
434*06f32e7eSjoerg       flushStreams(file_reporter);
435*06f32e7eSjoerg     }
436*06f32e7eSjoerg   }
437*06f32e7eSjoerg   console_reporter->Finalize();
438*06f32e7eSjoerg   if (file_reporter) file_reporter->Finalize();
439*06f32e7eSjoerg   flushStreams(console_reporter);
440*06f32e7eSjoerg   flushStreams(file_reporter);
441*06f32e7eSjoerg }
442*06f32e7eSjoerg 
CreateReporter(std::string const & name,ConsoleReporter::OutputOptions output_opts)443*06f32e7eSjoerg std::unique_ptr<BenchmarkReporter> CreateReporter(
444*06f32e7eSjoerg     std::string const& name, ConsoleReporter::OutputOptions output_opts) {
445*06f32e7eSjoerg   typedef std::unique_ptr<BenchmarkReporter> PtrType;
446*06f32e7eSjoerg   if (name == "console") {
447*06f32e7eSjoerg     return PtrType(new ConsoleReporter(output_opts));
448*06f32e7eSjoerg   } else if (name == "json") {
449*06f32e7eSjoerg     return PtrType(new JSONReporter);
450*06f32e7eSjoerg   } else if (name == "csv") {
451*06f32e7eSjoerg     return PtrType(new CSVReporter);
452*06f32e7eSjoerg   } else {
453*06f32e7eSjoerg     std::cerr << "Unexpected format: '" << name << "'\n";
454*06f32e7eSjoerg     std::exit(1);
455*06f32e7eSjoerg   }
456*06f32e7eSjoerg }
457*06f32e7eSjoerg 
458*06f32e7eSjoerg }  // end namespace
459*06f32e7eSjoerg 
IsZero(double n)460*06f32e7eSjoerg bool IsZero(double n) {
461*06f32e7eSjoerg   return std::abs(n) < std::numeric_limits<double>::epsilon();
462*06f32e7eSjoerg }
463*06f32e7eSjoerg 
GetOutputOptions(bool force_no_color)464*06f32e7eSjoerg ConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color) {
465*06f32e7eSjoerg   int output_opts = ConsoleReporter::OO_Defaults;
466*06f32e7eSjoerg   if ((FLAGS_benchmark_color == "auto" && IsColorTerminal()) ||
467*06f32e7eSjoerg       IsTruthyFlagValue(FLAGS_benchmark_color)) {
468*06f32e7eSjoerg     output_opts |= ConsoleReporter::OO_Color;
469*06f32e7eSjoerg   } else {
470*06f32e7eSjoerg     output_opts &= ~ConsoleReporter::OO_Color;
471*06f32e7eSjoerg   }
472*06f32e7eSjoerg   if(force_no_color) {
473*06f32e7eSjoerg     output_opts &= ~ConsoleReporter::OO_Color;
474*06f32e7eSjoerg   }
475*06f32e7eSjoerg   if(FLAGS_benchmark_counters_tabular) {
476*06f32e7eSjoerg     output_opts |= ConsoleReporter::OO_Tabular;
477*06f32e7eSjoerg   } else {
478*06f32e7eSjoerg     output_opts &= ~ConsoleReporter::OO_Tabular;
479*06f32e7eSjoerg   }
480*06f32e7eSjoerg   return static_cast< ConsoleReporter::OutputOptions >(output_opts);
481*06f32e7eSjoerg }
482*06f32e7eSjoerg 
483*06f32e7eSjoerg }  // end namespace internal
484*06f32e7eSjoerg 
RunSpecifiedBenchmarks()485*06f32e7eSjoerg size_t RunSpecifiedBenchmarks() {
486*06f32e7eSjoerg   return RunSpecifiedBenchmarks(nullptr, nullptr);
487*06f32e7eSjoerg }
488*06f32e7eSjoerg 
RunSpecifiedBenchmarks(BenchmarkReporter * console_reporter)489*06f32e7eSjoerg size_t RunSpecifiedBenchmarks(BenchmarkReporter* console_reporter) {
490*06f32e7eSjoerg   return RunSpecifiedBenchmarks(console_reporter, nullptr);
491*06f32e7eSjoerg }
492*06f32e7eSjoerg 
RunSpecifiedBenchmarks(BenchmarkReporter * console_reporter,BenchmarkReporter * file_reporter)493*06f32e7eSjoerg size_t RunSpecifiedBenchmarks(BenchmarkReporter* console_reporter,
494*06f32e7eSjoerg                               BenchmarkReporter* file_reporter) {
495*06f32e7eSjoerg   std::string spec = FLAGS_benchmark_filter;
496*06f32e7eSjoerg   if (spec.empty() || spec == "all")
497*06f32e7eSjoerg     spec = ".";  // Regexp that matches all benchmarks
498*06f32e7eSjoerg 
499*06f32e7eSjoerg   // Setup the reporters
500*06f32e7eSjoerg   std::ofstream output_file;
501*06f32e7eSjoerg   std::unique_ptr<BenchmarkReporter> default_console_reporter;
502*06f32e7eSjoerg   std::unique_ptr<BenchmarkReporter> default_file_reporter;
503*06f32e7eSjoerg   if (!console_reporter) {
504*06f32e7eSjoerg     default_console_reporter = internal::CreateReporter(
505*06f32e7eSjoerg           FLAGS_benchmark_format, internal::GetOutputOptions());
506*06f32e7eSjoerg     console_reporter = default_console_reporter.get();
507*06f32e7eSjoerg   }
508*06f32e7eSjoerg   auto& Out = console_reporter->GetOutputStream();
509*06f32e7eSjoerg   auto& Err = console_reporter->GetErrorStream();
510*06f32e7eSjoerg 
511*06f32e7eSjoerg   std::string const& fname = FLAGS_benchmark_out;
512*06f32e7eSjoerg   if (fname.empty() && file_reporter) {
513*06f32e7eSjoerg     Err << "A custom file reporter was provided but "
514*06f32e7eSjoerg            "--benchmark_out=<file> was not specified."
515*06f32e7eSjoerg         << std::endl;
516*06f32e7eSjoerg     std::exit(1);
517*06f32e7eSjoerg   }
518*06f32e7eSjoerg   if (!fname.empty()) {
519*06f32e7eSjoerg     output_file.open(fname);
520*06f32e7eSjoerg     if (!output_file.is_open()) {
521*06f32e7eSjoerg       Err << "invalid file name: '" << fname << std::endl;
522*06f32e7eSjoerg       std::exit(1);
523*06f32e7eSjoerg     }
524*06f32e7eSjoerg     if (!file_reporter) {
525*06f32e7eSjoerg       default_file_reporter = internal::CreateReporter(
526*06f32e7eSjoerg           FLAGS_benchmark_out_format, ConsoleReporter::OO_None);
527*06f32e7eSjoerg       file_reporter = default_file_reporter.get();
528*06f32e7eSjoerg     }
529*06f32e7eSjoerg     file_reporter->SetOutputStream(&output_file);
530*06f32e7eSjoerg     file_reporter->SetErrorStream(&output_file);
531*06f32e7eSjoerg   }
532*06f32e7eSjoerg 
533*06f32e7eSjoerg   std::vector<internal::Benchmark::Instance> benchmarks;
534*06f32e7eSjoerg   if (!FindBenchmarksInternal(spec, &benchmarks, &Err)) return 0;
535*06f32e7eSjoerg 
536*06f32e7eSjoerg   if (benchmarks.empty()) {
537*06f32e7eSjoerg     Err << "Failed to match any benchmarks against regex: " << spec << "\n";
538*06f32e7eSjoerg     return 0;
539*06f32e7eSjoerg   }
540*06f32e7eSjoerg 
541*06f32e7eSjoerg   if (FLAGS_benchmark_list_tests) {
542*06f32e7eSjoerg     for (auto const& benchmark : benchmarks) Out << benchmark.name << "\n";
543*06f32e7eSjoerg   } else {
544*06f32e7eSjoerg     internal::RunBenchmarks(benchmarks, console_reporter, file_reporter);
545*06f32e7eSjoerg   }
546*06f32e7eSjoerg 
547*06f32e7eSjoerg   return benchmarks.size();
548*06f32e7eSjoerg }
549*06f32e7eSjoerg 
550*06f32e7eSjoerg namespace internal {
551*06f32e7eSjoerg 
PrintUsageAndExit()552*06f32e7eSjoerg void PrintUsageAndExit() {
553*06f32e7eSjoerg   fprintf(stdout,
554*06f32e7eSjoerg           "benchmark"
555*06f32e7eSjoerg           " [--benchmark_list_tests={true|false}]\n"
556*06f32e7eSjoerg           "          [--benchmark_filter=<regex>]\n"
557*06f32e7eSjoerg           "          [--benchmark_min_time=<min_time>]\n"
558*06f32e7eSjoerg           "          [--benchmark_repetitions=<num_repetitions>]\n"
559*06f32e7eSjoerg           "          [--benchmark_report_aggregates_only={true|false}\n"
560*06f32e7eSjoerg           "          [--benchmark_format=<console|json|csv>]\n"
561*06f32e7eSjoerg           "          [--benchmark_out=<filename>]\n"
562*06f32e7eSjoerg           "          [--benchmark_out_format=<json|console|csv>]\n"
563*06f32e7eSjoerg           "          [--benchmark_color={auto|true|false}]\n"
564*06f32e7eSjoerg           "          [--benchmark_counters_tabular={true|false}]\n"
565*06f32e7eSjoerg           "          [--v=<verbosity>]\n");
566*06f32e7eSjoerg   exit(0);
567*06f32e7eSjoerg }
568*06f32e7eSjoerg 
ParseCommandLineFlags(int * argc,char ** argv)569*06f32e7eSjoerg void ParseCommandLineFlags(int* argc, char** argv) {
570*06f32e7eSjoerg   using namespace benchmark;
571*06f32e7eSjoerg   BenchmarkReporter::Context::executable_name = argv[0];
572*06f32e7eSjoerg   for (int i = 1; i < *argc; ++i) {
573*06f32e7eSjoerg     if (ParseBoolFlag(argv[i], "benchmark_list_tests",
574*06f32e7eSjoerg                       &FLAGS_benchmark_list_tests) ||
575*06f32e7eSjoerg         ParseStringFlag(argv[i], "benchmark_filter", &FLAGS_benchmark_filter) ||
576*06f32e7eSjoerg         ParseDoubleFlag(argv[i], "benchmark_min_time",
577*06f32e7eSjoerg                         &FLAGS_benchmark_min_time) ||
578*06f32e7eSjoerg         ParseInt32Flag(argv[i], "benchmark_repetitions",
579*06f32e7eSjoerg                        &FLAGS_benchmark_repetitions) ||
580*06f32e7eSjoerg         ParseBoolFlag(argv[i], "benchmark_report_aggregates_only",
581*06f32e7eSjoerg                       &FLAGS_benchmark_report_aggregates_only) ||
582*06f32e7eSjoerg         ParseStringFlag(argv[i], "benchmark_format", &FLAGS_benchmark_format) ||
583*06f32e7eSjoerg         ParseStringFlag(argv[i], "benchmark_out", &FLAGS_benchmark_out) ||
584*06f32e7eSjoerg         ParseStringFlag(argv[i], "benchmark_out_format",
585*06f32e7eSjoerg                         &FLAGS_benchmark_out_format) ||
586*06f32e7eSjoerg         ParseStringFlag(argv[i], "benchmark_color", &FLAGS_benchmark_color) ||
587*06f32e7eSjoerg         // "color_print" is the deprecated name for "benchmark_color".
588*06f32e7eSjoerg         // TODO: Remove this.
589*06f32e7eSjoerg         ParseStringFlag(argv[i], "color_print", &FLAGS_benchmark_color) ||
590*06f32e7eSjoerg         ParseBoolFlag(argv[i], "benchmark_counters_tabular",
591*06f32e7eSjoerg                         &FLAGS_benchmark_counters_tabular) ||
592*06f32e7eSjoerg         ParseInt32Flag(argv[i], "v", &FLAGS_v)) {
593*06f32e7eSjoerg       for (int j = i; j != *argc - 1; ++j) argv[j] = argv[j + 1];
594*06f32e7eSjoerg 
595*06f32e7eSjoerg       --(*argc);
596*06f32e7eSjoerg       --i;
597*06f32e7eSjoerg     } else if (IsFlag(argv[i], "help")) {
598*06f32e7eSjoerg       PrintUsageAndExit();
599*06f32e7eSjoerg     }
600*06f32e7eSjoerg   }
601*06f32e7eSjoerg   for (auto const* flag :
602*06f32e7eSjoerg        {&FLAGS_benchmark_format, &FLAGS_benchmark_out_format})
603*06f32e7eSjoerg     if (*flag != "console" && *flag != "json" && *flag != "csv") {
604*06f32e7eSjoerg       PrintUsageAndExit();
605*06f32e7eSjoerg     }
606*06f32e7eSjoerg   if (FLAGS_benchmark_color.empty()) {
607*06f32e7eSjoerg     PrintUsageAndExit();
608*06f32e7eSjoerg   }
609*06f32e7eSjoerg }
610*06f32e7eSjoerg 
InitializeStreams()611*06f32e7eSjoerg int InitializeStreams() {
612*06f32e7eSjoerg   static std::ios_base::Init init;
613*06f32e7eSjoerg   return 0;
614*06f32e7eSjoerg }
615*06f32e7eSjoerg 
616*06f32e7eSjoerg }  // end namespace internal
617*06f32e7eSjoerg 
Initialize(int * argc,char ** argv)618*06f32e7eSjoerg void Initialize(int* argc, char** argv) {
619*06f32e7eSjoerg   internal::ParseCommandLineFlags(argc, argv);
620*06f32e7eSjoerg   internal::LogLevel() = FLAGS_v;
621*06f32e7eSjoerg }
622*06f32e7eSjoerg 
ReportUnrecognizedArguments(int argc,char ** argv)623*06f32e7eSjoerg bool ReportUnrecognizedArguments(int argc, char** argv) {
624*06f32e7eSjoerg   for (int i = 1; i < argc; ++i) {
625*06f32e7eSjoerg     fprintf(stderr, "%s: error: unrecognized command-line flag: %s\n", argv[0], argv[i]);
626*06f32e7eSjoerg   }
627*06f32e7eSjoerg   return argc > 1;
628*06f32e7eSjoerg }
629*06f32e7eSjoerg 
630*06f32e7eSjoerg }  // end namespace benchmark
631