2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 // @author Andrei Alexandrescu (andrei.alexandrescu@fb.com)
19 #include <folly/Benchmark.h>
30 #include <boost/regex.hpp>
32 #include <folly/Foreach.h>
33 #include <folly/MapUtil.h>
34 #include <folly/String.h>
35 #include <folly/json.h>
39 DEFINE_bool(benchmark, false, "Run benchmarks.");
40 DEFINE_bool(json, false, "Output in JSON format.");
41 DEFINE_bool(json_verbose, false, "Output in verbose JSON format.");
46 "Only benchmarks whose names match this regex will be run.");
51 "Minimum # of microseconds we'll accept for each benchmark.");
56 "Minimum # of iterations we'll try for each benchmark.");
61 "Maximum # of iterations we'll try for each benchmark.");
66 "Maximum # of seconds we'll spend on each benchmark.");
70 std::chrono::high_resolution_clock::duration BenchmarkSuspender::timeSpent;
72 typedef function<detail::TimeIterPair(unsigned int)> BenchmarkFun;
74 vector<detail::BenchmarkRegistration>& benchmarks() {
75 static vector<detail::BenchmarkRegistration> _benchmarks;
79 #define FB_FOLLY_GLOBAL_BENCHMARK_BASELINE fbFollyGlobalBenchmarkBaseline
80 #define FB_STRINGIZE_X2(x) FB_STRINGIZE(x)
82 // Add the global baseline
83 BENCHMARK(FB_FOLLY_GLOBAL_BENCHMARK_BASELINE) {
91 size_t getGlobalBenchmarkBaselineIndex() {
92 const char *global = FB_STRINGIZE_X2(FB_FOLLY_GLOBAL_BENCHMARK_BASELINE);
93 auto it = std::find_if(
96 [global](const detail::BenchmarkRegistration& v) {
97 return v.name == global;
99 CHECK(it != benchmarks().end());
100 return size_t(std::distance(benchmarks().begin(), it));
103 #undef FB_STRINGIZE_X2
104 #undef FB_FOLLY_GLOBAL_BENCHMARK_BASELINE
106 void detail::addBenchmarkImpl(const char* file, const char* name,
108 benchmarks().push_back({file, name, std::move(fun)});
112 * Given a bunch of benchmark samples, estimate the actual run time.
114 static double estimateTime(double * begin, double * end) {
117 // Current state of the art: get the minimum. After some
118 // experimentation, it seems taking the minimum is the best.
119 return *min_element(begin, end);
122 static double runBenchmarkGetNSPerIteration(const BenchmarkFun& fun,
123 const double globalBaseline) {
124 using std::chrono::duration_cast;
125 using std::chrono::high_resolution_clock;
126 using std::chrono::microseconds;
127 using std::chrono::nanoseconds;
128 using std::chrono::seconds;
130 // They key here is accuracy; too low numbers means the accuracy was
131 // coarse. We up the ante until we get to at least minNanoseconds
134 std::is_same<high_resolution_clock::duration, nanoseconds>::value,
135 "High resolution clock must be nanosecond resolution.");
136 // We choose a minimum minimum (sic) of 100,000 nanoseconds, but if
137 // the clock resolution is worse than that, it will be larger. In
138 // essence we're aiming at making the quantization noise 0.01%.
139 static const auto minNanoseconds = std::max<nanoseconds>(
140 nanoseconds(100000), microseconds(FLAGS_bm_min_usec));
142 // We do measurements in several epochs and take the minimum, to
143 // account for jitter.
144 static const unsigned int epochs = 1000;
145 // We establish a total time budget as we don't want a measurement
146 // to take too long. This will curtail the number of actual epochs.
147 const auto timeBudget = seconds(FLAGS_bm_max_secs);
148 auto global = high_resolution_clock::now();
150 double epochResults[epochs] = { 0 };
151 size_t actualEpochs = 0;
153 for (; actualEpochs < epochs; ++actualEpochs) {
154 const auto maxIters = uint32_t(FLAGS_bm_max_iters);
155 for (auto n = uint32_t(FLAGS_bm_min_iters); n < maxIters; n *= 2) {
156 auto const nsecsAndIter = fun(static_cast<unsigned int>(n));
157 if (nsecsAndIter.first < minNanoseconds) {
160 // We got an accurate enough timing, done. But only save if
161 // smaller than the current result.
162 auto nsecs = duration_cast<nanoseconds>(nsecsAndIter.first).count();
163 epochResults[actualEpochs] =
164 max(0.0, double(nsecs) / nsecsAndIter.second - globalBaseline);
165 // Done with the current epoch, we got a meaningful timing.
168 auto now = high_resolution_clock::now();
169 if (now - global >= timeBudget) {
170 // No more time budget available.
176 // If the benchmark was basically drowned in baseline noise, it's
177 // possible it became negative.
178 return max(0.0, estimateTime(epochResults, epochResults + actualEpochs));
186 static const ScaleInfo kTimeSuffixes[] {
187 { 365.25 * 24 * 3600, "years" },
188 { 24 * 3600, "days" },
200 static const ScaleInfo kMetricSuffixes[] {
201 { 1E24, "Y" }, // yotta
202 { 1E21, "Z" }, // zetta
203 { 1E18, "X" }, // "exa" written with suffix 'X' so as to not create
204 // confusion with scientific notation
205 { 1E15, "P" }, // peta
206 { 1E12, "T" }, // terra
207 { 1E9, "G" }, // giga
208 { 1E6, "M" }, // mega
209 { 1E3, "K" }, // kilo
211 { 1E-3, "m" }, // milli
212 { 1E-6, "u" }, // micro
213 { 1E-9, "n" }, // nano
214 { 1E-12, "p" }, // pico
215 { 1E-15, "f" }, // femto
216 { 1E-18, "a" }, // atto
217 { 1E-21, "z" }, // zepto
218 { 1E-24, "y" }, // yocto
222 static string humanReadable(double n, unsigned int decimals,
223 const ScaleInfo* scales) {
224 if (std::isinf(n) || std::isnan(n)) {
225 return folly::to<string>(n);
228 const double absValue = fabs(n);
229 const ScaleInfo* scale = scales;
230 while (absValue < scale[0].boundary && scale[1].suffix != nullptr) {
234 const double scaledValue = n / scale->boundary;
235 return stringPrintf("%.*f%s", decimals, scaledValue, scale->suffix);
238 static string readableTime(double n, unsigned int decimals) {
239 return humanReadable(n, decimals, kTimeSuffixes);
242 static string metricReadable(double n, unsigned int decimals) {
243 return humanReadable(n, decimals, kMetricSuffixes);
246 static void printBenchmarkResultsAsTable(
247 const vector<detail::BenchmarkResult>& data) {
249 static const unsigned int columns = 76;
251 // Compute the longest benchmark name
252 size_t longestName = 0;
253 for (auto& bm : benchmarks()) {
254 longestName = max(longestName, bm.name.size());
257 // Print a horizontal rule
258 auto separator = [&](char pad) {
259 puts(string(columns, pad).c_str());
262 // Print header for a file
263 auto header = [&](const string& file) {
265 printf("%-*srelative time/iter iters/s\n",
266 columns - 28, file.c_str());
270 double baselineNsPerIter = numeric_limits<double>::max();
273 for (auto& datum : data) {
274 auto file = datum.file;
275 if (file != lastFile) {
281 string s = datum.name;
286 bool useBaseline /* = void */;
291 baselineNsPerIter = datum.timeInNs;
294 s.resize(columns - 29, ' ');
295 auto nsPerIter = datum.timeInNs;
296 auto secPerIter = nsPerIter / 1E9;
297 auto itersPerSec = (secPerIter == 0)
298 ? std::numeric_limits<double>::infinity()
301 // Print without baseline
302 printf("%*s %9s %7s\n",
303 static_cast<int>(s.size()), s.c_str(),
304 readableTime(secPerIter, 2).c_str(),
305 metricReadable(itersPerSec, 2).c_str());
307 // Print with baseline
308 auto rel = baselineNsPerIter / nsPerIter * 100.0;
309 printf("%*s %7.2f%% %9s %7s\n",
310 static_cast<int>(s.size()), s.c_str(),
312 readableTime(secPerIter, 2).c_str(),
313 metricReadable(itersPerSec, 2).c_str());
319 static void printBenchmarkResultsAsJson(
320 const vector<detail::BenchmarkResult>& data) {
321 dynamic d = dynamic::object;
322 for (auto& datum: data) {
323 d[datum.name] = datum.timeInNs * 1000.;
326 printf("%s\n", toPrettyJson(d).c_str());
329 static void printBenchmarkResultsAsVerboseJson(
330 const vector<detail::BenchmarkResult>& data) {
332 benchmarkResultsToDynamic(data, d);
333 printf("%s\n", toPrettyJson(d).c_str());
336 static void printBenchmarkResults(const vector<detail::BenchmarkResult>& data) {
337 if (FLAGS_json_verbose) {
338 printBenchmarkResultsAsVerboseJson(data);
339 } else if (FLAGS_json) {
340 printBenchmarkResultsAsJson(data);
342 printBenchmarkResultsAsTable(data);
346 void benchmarkResultsToDynamic(
347 const vector<detail::BenchmarkResult>& data,
349 out = dynamic::array;
350 for (auto& datum : data) {
351 out.push_back(dynamic::array(datum.file, datum.name, datum.timeInNs));
355 void benchmarkResultsFromDynamic(
357 vector<detail::BenchmarkResult>& results) {
358 for (auto& datum : d) {
360 {datum[0].asString(), datum[1].asString(), datum[2].asDouble()});
364 static pair<StringPiece, StringPiece> resultKey(
365 const detail::BenchmarkResult& result) {
366 return pair<StringPiece, StringPiece>(result.file, result.name);
369 void printResultComparison(
370 const vector<detail::BenchmarkResult>& base,
371 const vector<detail::BenchmarkResult>& test) {
372 map<pair<StringPiece, StringPiece>, double> baselines;
374 for (auto& baseResult : base) {
375 baselines[resultKey(baseResult)] = baseResult.timeInNs;
379 static const unsigned int columns = 76;
381 // Compute the longest benchmark name
382 size_t longestName = 0;
383 for (auto& datum : test) {
384 longestName = max(longestName, datum.name.size());
387 // Print a horizontal rule
388 auto separator = [&](char pad) { puts(string(columns, pad).c_str()); };
390 // Print header for a file
391 auto header = [&](const string& file) {
393 printf("%-*srelative time/iter iters/s\n", columns - 28, file.c_str());
399 for (auto& datum : test) {
400 folly::Optional<double> baseline =
401 folly::get_optional(baselines, resultKey(datum));
402 auto file = datum.file;
403 if (file != lastFile) {
409 string s = datum.name;
417 s.resize(columns - 29, ' ');
418 auto nsPerIter = datum.timeInNs;
419 auto secPerIter = nsPerIter / 1E9;
420 auto itersPerSec = (secPerIter == 0)
421 ? std::numeric_limits<double>::infinity()
424 // Print without baseline
427 static_cast<int>(s.size()),
429 readableTime(secPerIter, 2).c_str(),
430 metricReadable(itersPerSec, 2).c_str());
432 // Print with baseline
433 auto rel = *baseline / nsPerIter * 100.0;
435 "%*s %7.2f%% %9s %7s\n",
436 static_cast<int>(s.size()),
439 readableTime(secPerIter, 2).c_str(),
440 metricReadable(itersPerSec, 2).c_str());
446 void runBenchmarks() {
447 CHECK(!benchmarks().empty());
449 vector<detail::BenchmarkResult> results;
450 results.reserve(benchmarks().size() - 1);
452 std::unique_ptr<boost::regex> bmRegex;
453 if (!FLAGS_bm_regex.empty()) {
454 bmRegex.reset(new boost::regex(FLAGS_bm_regex));
457 // PLEASE KEEP QUIET. MEASUREMENTS IN PROGRESS.
459 size_t baselineIndex = getGlobalBenchmarkBaselineIndex();
461 auto const globalBaseline =
462 runBenchmarkGetNSPerIteration(benchmarks()[baselineIndex].func, 0);
463 FOR_EACH_RANGE (i, 0, benchmarks().size()) {
464 if (i == baselineIndex) {
467 double elapsed = 0.0;
468 auto& bm = benchmarks()[i];
469 if (bm.name != "-") { // skip separators
470 if (bmRegex && !boost::regex_search(bm.name, *bmRegex)) {
473 elapsed = runBenchmarkGetNSPerIteration(bm.func, globalBaseline);
475 results.push_back({bm.file, bm.name, elapsed});
478 // PLEASE MAKE NOISE. MEASUREMENTS DONE.
480 printBenchmarkResults(results);