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,
214 min<uint64_t>(resolutionInNs * 100000, 1000000000ULL));
216 // We do measurements in several epochs and take the minimum, to
217 // account for jitter.
218 static const unsigned int epochs = 1000;
219 // We establish a total time budget as we don't want a measurement
220 // to take too long. This will curtail the number of actual epochs.
221 const uint64_t timeBudgetInNs = FLAGS_bm_max_secs * 1000000000;
223 CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &global));
225 double epochResults[epochs] = { 0 };
226 size_t actualEpochs = 0;
228 for (; actualEpochs < epochs; ++actualEpochs) {
229 for (unsigned int n = FLAGS_bm_min_iters; n < (1UL << 30); n *= 2) {
230 auto const nsecs = fun(n);
231 if (nsecs < minNanoseconds) {
234 // We got an accurate enough timing, done. But only save if
235 // smaller than the current result.
236 epochResults[actualEpochs] = max(0.0, double(nsecs) / n - globalBaseline);
237 // Done with the current epoch, we got a meaningful timing.
241 CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &now));
242 if (detail::timespecDiff(now, global) >= timeBudgetInNs) {
243 // No more time budget available.
249 // If the benchmark was basically drowned in baseline noise, it's
250 // possible it became negative.
251 return max(0.0, estimateTime(epochResults, epochResults + actualEpochs));
259 static const ScaleInfo kTimeSuffixes[] {
260 { 365.25 * 24 * 3600, "years" },
261 { 24 * 3600, "days" },
273 static const ScaleInfo kMetricSuffixes[] {
274 { 1E24, "Y" }, // yotta
275 { 1E21, "Z" }, // zetta
276 { 1E18, "X" }, // "exa" written with suffix 'X' so as to not create
277 // confusion with scientific notation
278 { 1E15, "P" }, // peta
279 { 1E12, "T" }, // terra
280 { 1E9, "G" }, // giga
281 { 1E6, "M" }, // mega
282 { 1E3, "K" }, // kilo
284 { 1E-3, "m" }, // milli
285 { 1E-6, "u" }, // micro
286 { 1E-9, "n" }, // nano
287 { 1E-12, "p" }, // pico
288 { 1E-15, "f" }, // femto
289 { 1E-18, "a" }, // atto
290 { 1E-21, "z" }, // zepto
291 { 1E-24, "y" }, // yocto
295 static string humanReadable(double n, unsigned int decimals,
296 const ScaleInfo* scales) {
297 if (std::isinf(n) || std::isnan(n)) {
298 return folly::to<string>(n);
301 const double absValue = fabs(n);
302 const ScaleInfo* scale = scales;
303 while (absValue < scale[0].boundary && scale[1].suffix != NULL) {
307 const double scaledValue = n / scale->boundary;
308 return stringPrintf("%.*f%s", decimals, scaledValue, scale->suffix);
311 static string readableTime(double n, unsigned int decimals) {
312 return humanReadable(n, decimals, kTimeSuffixes);
315 static string metricReadable(double n, unsigned int decimals) {
316 return humanReadable(n, decimals, kMetricSuffixes);
319 static void printBenchmarkResultsAsTable(
320 const vector<tuple<const char*, const char*, double> >& data) {
322 static const uint columns = 76;
324 // Compute the longest benchmark name
325 size_t longestName = 0;
326 FOR_EACH_RANGE (i, 1, benchmarks.size()) {
327 longestName = max(longestName, strlen(get<1>(benchmarks[i])));
330 // Print a horizontal rule
331 auto separator = [&](char pad) {
332 puts(string(columns, pad).c_str());
335 // Print header for a file
336 auto header = [&](const char* file) {
338 printf("%-*srelative time/iter iters/s\n",
343 double baselineNsPerIter = numeric_limits<double>::max();
344 const char* lastFile = "";
346 for (auto& datum : data) {
347 auto file = get<0>(datum);
348 if (strcmp(file, lastFile)) {
354 string s = get<1>(datum);
359 bool useBaseline /* = void */;
364 baselineNsPerIter = get<2>(datum);
367 s.resize(columns - 29, ' ');
368 auto nsPerIter = get<2>(datum);
369 auto secPerIter = nsPerIter / 1E9;
370 auto itersPerSec = 1 / secPerIter;
372 // Print without baseline
373 printf("%*s %9s %7s\n",
374 static_cast<int>(s.size()), s.c_str(),
375 readableTime(secPerIter, 2).c_str(),
376 metricReadable(itersPerSec, 2).c_str());
378 // Print with baseline
379 auto rel = baselineNsPerIter / nsPerIter * 100.0;
380 printf("%*s %7.2f%% %9s %7s\n",
381 static_cast<int>(s.size()), s.c_str(),
383 readableTime(secPerIter, 2).c_str(),
384 metricReadable(itersPerSec, 2).c_str());
390 static void printBenchmarkResultsAsJson(
391 const vector<tuple<const char*, const char*, double> >& data) {
392 dynamic d = dynamic::object;
393 for (auto& datum: data) {
394 d[std::get<1>(datum)] = std::get<2>(datum) * 1000.;
397 printf("%s\n", toPrettyJson(d).c_str());
400 static void printBenchmarkResults(
401 const vector<tuple<const char*, const char*, double> >& data) {
404 printBenchmarkResultsAsJson(data);
406 printBenchmarkResultsAsTable(data);
410 void runBenchmarks() {
411 CHECK(!benchmarks.empty());
413 vector<tuple<const char*, const char*, double>> results;
414 results.reserve(benchmarks.size() - 1);
416 std::unique_ptr<boost::regex> bmRegex;
417 if (!FLAGS_bm_regex.empty()) {
418 bmRegex.reset(new boost::regex(FLAGS_bm_regex));
421 // PLEASE KEEP QUIET. MEASUREMENTS IN PROGRESS.
423 auto const globalBaseline = runBenchmarkGetNSPerIteration(
424 get<2>(benchmarks.front()), 0);
425 FOR_EACH_RANGE (i, 1, benchmarks.size()) {
426 double elapsed = 0.0;
427 if (!strcmp(get<1>(benchmarks[i]), "-") == 0) { // skip separators
428 if (bmRegex && !boost::regex_search(get<1>(benchmarks[i]), *bmRegex)) {
431 elapsed = runBenchmarkGetNSPerIteration(get<2>(benchmarks[i]),
434 results.emplace_back(get<0>(benchmarks[i]),
435 get<1>(benchmarks[i]), elapsed);
438 // PLEASE MAKE NOISE. MEASUREMENTS DONE.
440 printBenchmarkResults(results);