2 * Copyright 2013 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 "Benchmark.h"
25 #include <boost/regex.hpp>
34 DEFINE_bool(benchmark, false, "Run benchmarks.");
35 DEFINE_bool(json, false, "Output in JSON format.");
37 DEFINE_string(bm_regex, "",
38 "Only benchmarks whose names match this regex will be run.");
40 DEFINE_int64(bm_min_usec, 100,
41 "Minimum # of microseconds we'll accept for each benchmark.");
43 DEFINE_int64(bm_min_iters, 1,
44 "Minimum # of iterations we'll try for each benchmark.");
46 DEFINE_int32(bm_max_secs, 1,
47 "Maximum # of seconds we'll spend on each benchmark.");
52 BenchmarkSuspender::NanosecondsSpent BenchmarkSuspender::nsSpent;
54 typedef function<uint64_t(unsigned int)> BenchmarkFun;
55 static vector<tuple<const char*, const char*, BenchmarkFun>> benchmarks;
57 // Add the global baseline
58 BENCHMARK(globalBenchmarkBaseline) {
62 void detail::addBenchmarkImpl(const char* file, const char* name,
64 benchmarks.emplace_back(file, name, std::move(fun));
68 * Given a point, gives density at that point as a number 0.0 < x <=
69 * 1.0. The result is 1.0 if all samples are equal to where, and
70 * decreases near 0 if all points are far away from it. The density is
71 * computed with the help of a radial basis function.
73 static double density(const double * begin, const double *const end,
74 const double where, const double bandwidth) {
76 assert(bandwidth > 0.0);
78 FOR_EACH_RANGE (i, begin, end) {
79 auto d = (*i - where) / bandwidth;
82 return sum / (end - begin);
86 * Computes mean and variance for a bunch of data points. Note that
87 * mean is currently not being used.
89 static pair<double, double>
90 meanVariance(const double * begin, const double *const end) {
92 double sum = 0.0, sum2 = 0.0;
93 FOR_EACH_RANGE (i, begin, end) {
97 auto const n = end - begin;
98 return make_pair(sum / n, sqrt((sum2 - sum * sum / n) / n));
102 * Computes the mode of a sample set through brute force. Assumes
105 static double mode(const double * begin, const double *const end) {
107 // Lower bound and upper bound for result and their respective
113 // Get the variance so we pass it down to density()
114 auto const sigma = meanVariance(begin, end).second;
116 // No variance means constant signal
120 FOR_EACH_RANGE (i, begin, end) {
121 assert(i == begin || *i >= i[-1]);
122 auto candidate = density(begin, end, *i, sigma * sqrt(2.0));
123 if (candidate > bestDensity) {
125 bestDensity = candidate;
128 // Density is decreasing... we could break here if we definitely
129 // knew this is unimodal.
137 * Given a bunch of benchmark samples, estimate the actual run time.
139 static double estimateTime(double * begin, double * end) {
142 // Current state of the art: get the minimum. After some
143 // experimentation, it seems taking the minimum is the best.
145 return *min_element(begin, end);
147 // What follows after estimates the time as the mode of the
150 // Select the awesomest (i.e. most frequent) result. We do this by
151 // sorting and then computing the longest run length.
154 // Eliminate outliers. A time much larger than the minimum time is
155 // considered an outlier.
156 while (end[-1] > 2.0 * *begin) {
166 /* Code used just for comparison purposes */ {
167 unsigned bestFrequency = 0;
168 unsigned candidateFrequency = 1;
169 double candidateValue = *begin;
170 for (auto current = begin + 1; ; ++current) {
171 if (current == end || *current != candidateValue) {
172 // Done with the current run, see if it was best
173 if (candidateFrequency > bestFrequency) {
174 bestFrequency = candidateFrequency;
175 result = candidateValue;
177 if (current == end) {
181 candidateValue = *current;
182 candidateFrequency = 1;
184 // Cool, inside a run, increase the frequency
185 ++candidateFrequency;
190 result = mode(begin, end);
195 static double runBenchmarkGetNSPerIteration(const BenchmarkFun& fun,
196 const double globalBaseline) {
197 // They key here is accuracy; too low numbers means the accuracy was
198 // coarse. We up the ante until we get to at least minNanoseconds
200 static uint64_t resolutionInNs = 0, coarseResolutionInNs = 0;
201 if (!resolutionInNs) {
203 CHECK_EQ(0, clock_getres(detail::DEFAULT_CLOCK_ID, &ts));
204 CHECK_EQ(0, ts.tv_sec) << "Clock sucks.";
205 CHECK_LT(0, ts.tv_nsec) << "Clock too fast for its own good.";
206 CHECK_EQ(1, ts.tv_nsec) << "Clock too coarse, upgrade your kernel.";
207 resolutionInNs = ts.tv_nsec;
209 // We choose a minimum minimum (sic) of 100,000 nanoseconds, but if
210 // the clock resolution is worse than that, it will be larger. In
211 // essence we're aiming at making the quantization noise 0.01%.
212 static const auto minNanoseconds =
213 max(FLAGS_bm_min_usec * 1000UL, min(resolutionInNs * 100000, 1000000000UL));
215 // We do measurements in several epochs and take the minimum, to
216 // account for jitter.
217 static const unsigned int epochs = 1000;
218 // We establish a total time budget as we don't want a measurement
219 // to take too long. This will curtail the number of actual epochs.
220 const uint64_t timeBudgetInNs = FLAGS_bm_max_secs * 1000000000;
222 CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &global));
224 double epochResults[epochs] = { 0 };
225 size_t actualEpochs = 0;
227 for (; actualEpochs < epochs; ++actualEpochs) {
228 for (unsigned int n = FLAGS_bm_min_iters; n < (1UL << 30); n *= 2) {
229 auto const nsecs = fun(n);
230 if (nsecs < minNanoseconds) {
233 // We got an accurate enough timing, done. But only save if
234 // smaller than the current result.
235 epochResults[actualEpochs] = max(0.0, double(nsecs) / n - globalBaseline);
236 // Done with the current epoch, we got a meaningful timing.
240 CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &now));
241 if (detail::timespecDiff(now, global) >= timeBudgetInNs) {
242 // No more time budget available.
248 // If the benchmark was basically drowned in baseline noise, it's
249 // possible it became negative.
250 return max(0.0, estimateTime(epochResults, epochResults + actualEpochs));
258 static const ScaleInfo kTimeSuffixes[] {
259 { 365.25 * 24 * 3600, "years" },
260 { 24 * 3600, "days" },
272 static const ScaleInfo kMetricSuffixes[] {
273 { 1E24, "Y" }, // yotta
274 { 1E21, "Z" }, // zetta
275 { 1E18, "X" }, // "exa" written with suffix 'X' so as to not create
276 // confusion with scientific notation
277 { 1E15, "P" }, // peta
278 { 1E12, "T" }, // terra
279 { 1E9, "G" }, // giga
280 { 1E6, "M" }, // mega
281 { 1E3, "K" }, // kilo
283 { 1E-3, "m" }, // milli
284 { 1E-6, "u" }, // micro
285 { 1E-9, "n" }, // nano
286 { 1E-12, "p" }, // pico
287 { 1E-15, "f" }, // femto
288 { 1E-18, "a" }, // atto
289 { 1E-21, "z" }, // zepto
290 { 1E-24, "y" }, // yocto
294 static string humanReadable(double n, unsigned int decimals,
295 const ScaleInfo* scales) {
296 if (std::isinf(n) || std::isnan(n)) {
297 return folly::to<string>(n);
300 const double absValue = fabs(n);
301 const ScaleInfo* scale = scales;
302 while (absValue < scale[0].boundary && scale[1].suffix != NULL) {
306 const double scaledValue = n / scale->boundary;
307 return stringPrintf("%.*f%s", decimals, scaledValue, scale->suffix);
310 static string readableTime(double n, unsigned int decimals) {
311 return humanReadable(n, decimals, kTimeSuffixes);
314 static string metricReadable(double n, unsigned int decimals) {
315 return humanReadable(n, decimals, kMetricSuffixes);
318 static void printBenchmarkResultsAsTable(
319 const vector<tuple<const char*, const char*, double> >& data) {
321 static const uint columns = 76;
323 // Compute the longest benchmark name
324 size_t longestName = 0;
325 FOR_EACH_RANGE (i, 1, benchmarks.size()) {
326 longestName = max(longestName, strlen(get<1>(benchmarks[i])));
329 // Print a horizontal rule
330 auto separator = [&](char pad) {
331 puts(string(columns, pad).c_str());
334 // Print header for a file
335 auto header = [&](const char* file) {
337 printf("%-*srelative time/iter iters/s\n",
342 double baselineNsPerIter = numeric_limits<double>::max();
343 const char* lastFile = "";
345 for (auto& datum : data) {
346 auto file = get<0>(datum);
347 if (strcmp(file, lastFile)) {
353 string s = get<1>(datum);
358 bool useBaseline /* = void */;
363 baselineNsPerIter = get<2>(datum);
366 s.resize(columns - 29, ' ');
367 auto nsPerIter = get<2>(datum);
368 auto secPerIter = nsPerIter / 1E9;
369 auto itersPerSec = 1 / secPerIter;
371 // Print without baseline
372 printf("%*s %9s %7s\n",
373 static_cast<int>(s.size()), s.c_str(),
374 readableTime(secPerIter, 2).c_str(),
375 metricReadable(itersPerSec, 2).c_str());
377 // Print with baseline
378 auto rel = baselineNsPerIter / nsPerIter * 100.0;
379 printf("%*s %7.2f%% %9s %7s\n",
380 static_cast<int>(s.size()), s.c_str(),
382 readableTime(secPerIter, 2).c_str(),
383 metricReadable(itersPerSec, 2).c_str());
389 static void printBenchmarkResultsAsJson(
390 const vector<tuple<const char*, const char*, double> >& data) {
391 dynamic d = dynamic::object;
392 for (auto& datum: data) {
393 d[std::get<1>(datum)] = std::get<2>(datum) * 1000.;
396 printf("%s\n", toPrettyJson(d).c_str());
399 static void printBenchmarkResults(
400 const vector<tuple<const char*, const char*, double> >& data) {
403 printBenchmarkResultsAsJson(data);
405 printBenchmarkResultsAsTable(data);
409 void runBenchmarks() {
410 CHECK(!benchmarks.empty());
412 vector<tuple<const char*, const char*, double>> results;
413 results.reserve(benchmarks.size() - 1);
415 std::unique_ptr<boost::regex> bmRegex;
416 if (!FLAGS_bm_regex.empty()) {
417 bmRegex.reset(new boost::regex(FLAGS_bm_regex));
420 // PLEASE KEEP QUIET. MEASUREMENTS IN PROGRESS.
422 auto const globalBaseline = runBenchmarkGetNSPerIteration(
423 get<2>(benchmarks.front()), 0);
424 FOR_EACH_RANGE (i, 1, benchmarks.size()) {
425 double elapsed = 0.0;
426 if (!strcmp(get<1>(benchmarks[i]), "-") == 0) { // skip separators
427 if (bmRegex && !boost::regex_search(get<1>(benchmarks[i]), *bmRegex)) {
430 elapsed = runBenchmarkGetNSPerIteration(get<2>(benchmarks[i]),
433 results.emplace_back(get<0>(benchmarks[i]),
434 get<1>(benchmarks[i]), elapsed);
437 // PLEASE MAKE NOISE. MEASUREMENTS DONE.
439 printBenchmarkResults(results);