2 * Copyright 2016 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>
20 #include <folly/Foreach.h>
21 #include <folly/json.h>
22 #include <folly/String.h>
25 #include <boost/regex.hpp>
35 DEFINE_bool(benchmark, false, "Run benchmarks.");
36 DEFINE_bool(json, false, "Output in JSON format.");
41 "Only benchmarks whose names match this regex will be run.");
46 "Minimum # of microseconds we'll accept for each benchmark.");
51 "Minimum # of iterations we'll try for each benchmark.");
56 "Maximum # of iterations we'll try for each benchmark.");
61 "Maximum # of seconds we'll spend on each benchmark.");
65 BenchmarkSuspender::NanosecondsSpent BenchmarkSuspender::nsSpent;
67 typedef function<detail::TimeIterPair(unsigned int)> BenchmarkFun;
70 vector<tuple<string, string, BenchmarkFun>>& benchmarks() {
71 static vector<tuple<string, string, BenchmarkFun>> _benchmarks;
75 #define FB_FOLLY_GLOBAL_BENCHMARK_BASELINE fbFollyGlobalBenchmarkBaseline
76 #define FB_STRINGIZE_X2(x) FB_STRINGIZE(x)
78 // Add the global baseline
79 BENCHMARK(FB_FOLLY_GLOBAL_BENCHMARK_BASELINE) {
87 int getGlobalBenchmarkBaselineIndex() {
88 const char *global = FB_STRINGIZE_X2(FB_FOLLY_GLOBAL_BENCHMARK_BASELINE);
89 auto it = std::find_if(
92 [global](const tuple<string, string, BenchmarkFun> &v) {
93 return get<1>(v) == global;
96 CHECK(it != benchmarks().end());
97 return it - benchmarks().begin();
100 #undef FB_STRINGIZE_X2
101 #undef FB_FOLLY_GLOBAL_BENCHMARK_BASELINE
103 void detail::addBenchmarkImpl(const char* file, const char* name,
105 benchmarks().emplace_back(file, name, std::move(fun));
109 * Given a point, gives density at that point as a number 0.0 < x <=
110 * 1.0. The result is 1.0 if all samples are equal to where, and
111 * decreases near 0 if all points are far away from it. The density is
112 * computed with the help of a radial basis function.
114 static double density(const double * begin, const double *const end,
115 const double where, const double bandwidth) {
117 assert(bandwidth > 0.0);
119 FOR_EACH_RANGE (i, begin, end) {
120 auto d = (*i - where) / bandwidth;
123 return sum / (end - begin);
127 * Computes mean and variance for a bunch of data points. Note that
128 * mean is currently not being used.
130 static pair<double, double>
131 meanVariance(const double * begin, const double *const end) {
133 double sum = 0.0, sum2 = 0.0;
134 FOR_EACH_RANGE (i, begin, end) {
138 auto const n = end - begin;
139 return make_pair(sum / n, sqrt((sum2 - sum * sum / n) / n));
143 * Computes the mode of a sample set through brute force. Assumes
146 static double mode(const double * begin, const double *const end) {
148 // Lower bound and upper bound for result and their respective
154 // Get the variance so we pass it down to density()
155 auto const sigma = meanVariance(begin, end).second;
157 // No variance means constant signal
161 FOR_EACH_RANGE (i, begin, end) {
162 assert(i == begin || *i >= i[-1]);
163 auto candidate = density(begin, end, *i, sigma * sqrt(2.0));
164 if (candidate > bestDensity) {
166 bestDensity = candidate;
169 // Density is decreasing... we could break here if we definitely
170 // knew this is unimodal.
178 * Given a bunch of benchmark samples, estimate the actual run time.
180 static double estimateTime(double * begin, double * end) {
183 // Current state of the art: get the minimum. After some
184 // experimentation, it seems taking the minimum is the best.
186 return *min_element(begin, end);
188 // What follows after estimates the time as the mode of the
191 // Select the awesomest (i.e. most frequent) result. We do this by
192 // sorting and then computing the longest run length.
195 // Eliminate outliers. A time much larger than the minimum time is
196 // considered an outlier.
197 while (end[-1] > 2.0 * *begin) {
207 /* Code used just for comparison purposes */ {
208 unsigned bestFrequency = 0;
209 unsigned candidateFrequency = 1;
210 double candidateValue = *begin;
211 for (auto current = begin + 1; ; ++current) {
212 if (current == end || *current != candidateValue) {
213 // Done with the current run, see if it was best
214 if (candidateFrequency > bestFrequency) {
215 bestFrequency = candidateFrequency;
216 result = candidateValue;
218 if (current == end) {
222 candidateValue = *current;
223 candidateFrequency = 1;
225 // Cool, inside a run, increase the frequency
226 ++candidateFrequency;
231 result = mode(begin, end);
236 static double runBenchmarkGetNSPerIteration(const BenchmarkFun& fun,
237 const double globalBaseline) {
238 // They key here is accuracy; too low numbers means the accuracy was
239 // coarse. We up the ante until we get to at least minNanoseconds
241 static uint64_t resolutionInNs = 0;
242 if (!resolutionInNs) {
244 CHECK_EQ(0, clock_getres(CLOCK_REALTIME, &ts));
245 CHECK_EQ(0, ts.tv_sec) << "Clock sucks.";
246 CHECK_LT(0, ts.tv_nsec) << "Clock too fast for its own good.";
247 CHECK_EQ(1, ts.tv_nsec) << "Clock too coarse, upgrade your kernel.";
248 resolutionInNs = ts.tv_nsec;
250 // We choose a minimum minimum (sic) of 100,000 nanoseconds, but if
251 // the clock resolution is worse than that, it will be larger. In
252 // essence we're aiming at making the quantization noise 0.01%.
253 static const auto minNanoseconds =
254 max<uint64_t>(FLAGS_bm_min_usec * 1000UL,
255 min<uint64_t>(resolutionInNs * 100000, 1000000000ULL));
257 // We do measurements in several epochs and take the minimum, to
258 // account for jitter.
259 static const unsigned int epochs = 1000;
260 // We establish a total time budget as we don't want a measurement
261 // to take too long. This will curtail the number of actual epochs.
262 const uint64_t timeBudgetInNs = FLAGS_bm_max_secs * 1000000000ULL;
264 CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &global));
266 double epochResults[epochs] = { 0 };
267 size_t actualEpochs = 0;
269 for (; actualEpochs < epochs; ++actualEpochs) {
270 const auto maxIters = FLAGS_bm_max_iters;
271 for (unsigned int n = FLAGS_bm_min_iters; n < maxIters; n *= 2) {
272 auto const nsecsAndIter = fun(n);
273 if (nsecsAndIter.first < minNanoseconds) {
276 // We got an accurate enough timing, done. But only save if
277 // smaller than the current result.
278 epochResults[actualEpochs] = max(0.0, double(nsecsAndIter.first) /
279 nsecsAndIter.second - globalBaseline);
280 // Done with the current epoch, we got a meaningful timing.
284 CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &now));
285 if (detail::timespecDiff(now, global) >= timeBudgetInNs) {
286 // No more time budget available.
292 // If the benchmark was basically drowned in baseline noise, it's
293 // possible it became negative.
294 return max(0.0, estimateTime(epochResults, epochResults + actualEpochs));
302 static const ScaleInfo kTimeSuffixes[] {
303 { 365.25 * 24 * 3600, "years" },
304 { 24 * 3600, "days" },
316 static const ScaleInfo kMetricSuffixes[] {
317 { 1E24, "Y" }, // yotta
318 { 1E21, "Z" }, // zetta
319 { 1E18, "X" }, // "exa" written with suffix 'X' so as to not create
320 // confusion with scientific notation
321 { 1E15, "P" }, // peta
322 { 1E12, "T" }, // terra
323 { 1E9, "G" }, // giga
324 { 1E6, "M" }, // mega
325 { 1E3, "K" }, // kilo
327 { 1E-3, "m" }, // milli
328 { 1E-6, "u" }, // micro
329 { 1E-9, "n" }, // nano
330 { 1E-12, "p" }, // pico
331 { 1E-15, "f" }, // femto
332 { 1E-18, "a" }, // atto
333 { 1E-21, "z" }, // zepto
334 { 1E-24, "y" }, // yocto
338 static string humanReadable(double n, unsigned int decimals,
339 const ScaleInfo* scales) {
340 if (std::isinf(n) || std::isnan(n)) {
341 return folly::to<string>(n);
344 const double absValue = fabs(n);
345 const ScaleInfo* scale = scales;
346 while (absValue < scale[0].boundary && scale[1].suffix != nullptr) {
350 const double scaledValue = n / scale->boundary;
351 return stringPrintf("%.*f%s", decimals, scaledValue, scale->suffix);
354 static string readableTime(double n, unsigned int decimals) {
355 return humanReadable(n, decimals, kTimeSuffixes);
358 static string metricReadable(double n, unsigned int decimals) {
359 return humanReadable(n, decimals, kMetricSuffixes);
362 static void printBenchmarkResultsAsTable(
363 const vector<tuple<string, string, double> >& data) {
365 static const unsigned int columns = 76;
367 // Compute the longest benchmark name
368 size_t longestName = 0;
369 FOR_EACH_RANGE (i, 1, benchmarks().size()) {
370 longestName = max(longestName, get<1>(benchmarks()[i]).size());
373 // Print a horizontal rule
374 auto separator = [&](char pad) {
375 puts(string(columns, pad).c_str());
378 // Print header for a file
379 auto header = [&](const string& file) {
381 printf("%-*srelative time/iter iters/s\n",
382 columns - 28, file.c_str());
386 double baselineNsPerIter = numeric_limits<double>::max();
389 for (auto& datum : data) {
390 auto file = get<0>(datum);
391 if (file != lastFile) {
397 string s = get<1>(datum);
402 bool useBaseline /* = void */;
407 baselineNsPerIter = get<2>(datum);
410 s.resize(columns - 29, ' ');
411 auto nsPerIter = get<2>(datum);
412 auto secPerIter = nsPerIter / 1E9;
413 auto itersPerSec = (secPerIter == 0)
414 ? std::numeric_limits<double>::infinity()
417 // Print without baseline
418 printf("%*s %9s %7s\n",
419 static_cast<int>(s.size()), s.c_str(),
420 readableTime(secPerIter, 2).c_str(),
421 metricReadable(itersPerSec, 2).c_str());
423 // Print with baseline
424 auto rel = baselineNsPerIter / nsPerIter * 100.0;
425 printf("%*s %7.2f%% %9s %7s\n",
426 static_cast<int>(s.size()), s.c_str(),
428 readableTime(secPerIter, 2).c_str(),
429 metricReadable(itersPerSec, 2).c_str());
435 static void printBenchmarkResultsAsJson(
436 const vector<tuple<string, string, double> >& data) {
437 dynamic d = dynamic::object;
438 for (auto& datum: data) {
439 d[std::get<1>(datum)] = std::get<2>(datum) * 1000.;
442 printf("%s\n", toPrettyJson(d).c_str());
445 static void printBenchmarkResults(
446 const vector<tuple<string, string, double> >& data) {
449 printBenchmarkResultsAsJson(data);
451 printBenchmarkResultsAsTable(data);
455 void runBenchmarks() {
456 CHECK(!benchmarks().empty());
458 vector<tuple<string, string, double>> results;
459 results.reserve(benchmarks().size() - 1);
461 std::unique_ptr<boost::regex> bmRegex;
462 if (!FLAGS_bm_regex.empty()) {
463 bmRegex.reset(new boost::regex(FLAGS_bm_regex));
466 // PLEASE KEEP QUIET. MEASUREMENTS IN PROGRESS.
468 unsigned int baselineIndex = getGlobalBenchmarkBaselineIndex();
470 auto const globalBaseline =
471 runBenchmarkGetNSPerIteration(get<2>(benchmarks()[baselineIndex]), 0);
472 FOR_EACH_RANGE (i, 0, benchmarks().size()) {
473 if (i == baselineIndex) {
476 double elapsed = 0.0;
477 if (get<1>(benchmarks()[i]) != "-") { // skip separators
478 if (bmRegex && !boost::regex_search(get<1>(benchmarks()[i]), *bmRegex)) {
481 elapsed = runBenchmarkGetNSPerIteration(get<2>(benchmarks()[i]),
484 results.emplace_back(get<0>(benchmarks()[i]),
485 get<1>(benchmarks()[i]), elapsed);
488 // PLEASE MAKE NOISE. MEASUREMENTS DONE.
490 printBenchmarkResults(results);