2 * Copyright 2012 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"
32 DEFINE_bool(benchmark, false, "Run benchmarks.");
33 DEFINE_bool(json, false, "Output in JSON format.");
37 BenchmarkSuspender::NanosecondsSpent BenchmarkSuspender::nsSpent;
39 typedef function<uint64_t(unsigned int)> BenchmarkFun;
40 static vector<tuple<const char*, const char*, BenchmarkFun>> benchmarks;
42 // Add the global baseline
43 BENCHMARK(globalBenchmarkBaseline) {
47 void detail::addBenchmarkImpl(const char* file, const char* name,
49 benchmarks.emplace_back(file, name, std::move(fun));
53 * Given a point, gives density at that point as a number 0.0 < x <=
54 * 1.0. The result is 1.0 if all samples are equal to where, and
55 * decreases near 0 if all points are far away from it. The density is
56 * computed with the help of a radial basis function.
58 static double density(const double * begin, const double *const end,
59 const double where, const double bandwidth) {
61 assert(bandwidth > 0.0);
63 FOR_EACH_RANGE (i, begin, end) {
64 auto d = (*i - where) / bandwidth;
67 return sum / (end - begin);
71 * Computes mean and variance for a bunch of data points. Note that
72 * mean is currently not being used.
74 static pair<double, double>
75 meanVariance(const double * begin, const double *const end) {
77 double sum = 0.0, sum2 = 0.0;
78 FOR_EACH_RANGE (i, begin, end) {
82 auto const n = end - begin;
83 return make_pair(sum / n, sqrt((sum2 - sum * sum / n) / n));
87 * Computes the mode of a sample set through brute force. Assumes
90 static double mode(const double * begin, const double *const end) {
92 // Lower bound and upper bound for result and their respective
98 // Get the variance so we pass it down to density()
99 auto const sigma = meanVariance(begin, end).second;
101 // No variance means constant signal
105 FOR_EACH_RANGE (i, begin, end) {
106 assert(i == begin || *i >= i[-1]);
107 auto candidate = density(begin, end, *i, sigma * sqrt(2.0));
108 if (candidate > bestDensity) {
110 bestDensity = candidate;
113 // Density is decreasing... we could break here if we definitely
114 // knew this is unimodal.
122 * Given a bunch of benchmark samples, estimate the actual run time.
124 static double estimateTime(double * begin, double * end) {
127 // Current state of the art: get the minimum. After some
128 // experimentation, it seems taking the minimum is the best.
130 return *min_element(begin, end);
132 // What follows after estimates the time as the mode of the
135 // Select the awesomest (i.e. most frequent) result. We do this by
136 // sorting and then computing the longest run length.
139 // Eliminate outliers. A time much larger than the minimum time is
140 // considered an outlier.
141 while (end[-1] > 2.0 * *begin) {
151 /* Code used just for comparison purposes */ {
152 unsigned bestFrequency = 0;
153 unsigned candidateFrequency = 1;
154 double candidateValue = *begin;
155 for (auto current = begin + 1; ; ++current) {
156 if (current == end || *current != candidateValue) {
157 // Done with the current run, see if it was best
158 if (candidateFrequency > bestFrequency) {
159 bestFrequency = candidateFrequency;
160 result = candidateValue;
162 if (current == end) {
166 candidateValue = *current;
167 candidateFrequency = 1;
169 // Cool, inside a run, increase the frequency
170 ++candidateFrequency;
175 result = mode(begin, end);
180 static double runBenchmarkGetNSPerIteration(const BenchmarkFun& fun,
181 const double globalBaseline) {
182 // They key here is accuracy; too low numbers means the accuracy was
183 // coarse. We up the ante until we get to at least minNanoseconds
185 static uint64_t resolutionInNs = 0, coarseResolutionInNs = 0;
186 if (!resolutionInNs) {
188 CHECK_EQ(0, clock_getres(detail::DEFAULT_CLOCK_ID, &ts));
189 CHECK_EQ(0, ts.tv_sec) << "Clock sucks.";
190 CHECK_LT(0, ts.tv_nsec) << "Clock too fast for its own good.";
191 CHECK_EQ(1, ts.tv_nsec) << "Clock too coarse, upgrade your kernel.";
192 resolutionInNs = ts.tv_nsec;
194 // Whe choose a minimum minimum (sic) of 10,000 nanoseconds, but if
195 // the clock resolution is worse than that, it will be larger. In
196 // essence we're aiming at making the quantization noise 0.01%.
197 static const auto minNanoseconds = min(resolutionInNs * 100000, 1000000000UL);
199 // We do measurements in several epochs and take the minimum, to
200 // account for jitter.
201 static const unsigned int epochs = 1000;
202 // We establish a total time budget as we don't want a measurement
203 // to take too long. This will curtail the number of actual epochs.
204 static const uint64_t timeBudgetInNs = 1000000000;
206 CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &global));
208 double epochResults[epochs] = { 0 };
209 size_t actualEpochs = 0;
211 for (; actualEpochs < epochs; ++actualEpochs) {
212 for (unsigned int n = 1; n < (1U << 30); n *= 2) {
213 auto const nsecs = fun(n);
214 if (nsecs < minNanoseconds) {
217 // We got an accurate enough timing, done. But only save if
218 // smaller than the current result.
219 epochResults[actualEpochs] = max(0.0, double(nsecs) / n - globalBaseline);
220 // Done with the current epoch, we got a meaningful timing.
224 CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &now));
225 if (detail::timespecDiff(now, global) >= timeBudgetInNs) {
226 // No more time budget available.
232 // If the benchmark was basically drowned in baseline noise, it's
233 // possible it became negative.
234 return max(0.0, estimateTime(epochResults, epochResults + actualEpochs));
237 static string humanReadable(double n, unsigned int decimals) {
242 // Too big to be comprehended by the puny human brain
245 } else if (a >= 1E18) {
246 // "EXA" written with suffix 'X' so as to not create confusion
247 // with scientific notation.
250 } else if (a >= 1E15) {
254 } else if (a >= 1E12) {
258 } else if (a >= 1E9) {
262 } else if (a >= 1E6) {
266 } else if (a >= 1E3) {
270 } else if (a == 0.0) {
272 } else if (a < 1E-15) {
276 } else if (a < 1E-12) {
280 } else if (a < 1E-9) {
284 } else if (a < 1E-6) {
288 } else if (a < 1E-3) {
298 return stringPrintf("%*.*f%c", decimals + 3 + 1, decimals, n, suffix);
301 static void printBenchmarkResultsAsTable(
302 const vector<tuple<const char*, const char*, double> >& data) {
304 static const uint columns = 76;
306 // Compute the longest benchmark name
307 size_t longestName = 0;
308 FOR_EACH_RANGE (i, 1, benchmarks.size()) {
309 longestName = max(longestName, strlen(get<1>(benchmarks[i])));
312 // Print a horizontal rule
313 auto separator = [&](char pad) {
314 puts(string(columns, pad).c_str());
317 // Print header for a file
318 auto header = [&](const char* file) {
320 printf("%-*srelative ns/iter iters/s\n",
325 double baselineNsPerIter = numeric_limits<double>::max();
326 const char* lastFile = "";
328 for (auto& datum : data) {
329 auto file = get<0>(datum);
330 if (strcmp(file, lastFile)) {
336 string s = get<1>(datum);
341 bool useBaseline /* = void */;
346 baselineNsPerIter = get<2>(datum);
349 s.resize(columns - 27, ' ');
350 auto nsPerIter = get<2>(datum);
351 auto itersPerSec = 1E9 / nsPerIter;
353 // Print without baseline
354 printf("%*s %s %s\n",
355 static_cast<int>(s.size()), s.c_str(),
356 humanReadable(nsPerIter, 2).c_str(),
357 humanReadable(itersPerSec, 2).c_str());
359 // Print with baseline
360 auto rel = baselineNsPerIter / nsPerIter * 100.0;
361 printf("%*s %7.2f%% %s %s\n",
362 static_cast<int>(s.size()), s.c_str(),
364 humanReadable(nsPerIter, 2).c_str(),
365 humanReadable(itersPerSec, 2).c_str());
371 static void printBenchmarkResultsAsJson(
372 const vector<tuple<const char*, const char*, double> >& data) {
373 dynamic d = dynamic::object;
374 for (auto& datum: data) {
375 d[std::get<1>(datum)] = std::get<2>(datum) * 1000.;
378 printf("%s\n", toPrettyJson(d).c_str());
381 static void printBenchmarkResults(
382 const vector<tuple<const char*, const char*, double> >& data) {
385 printBenchmarkResultsAsJson(data);
387 printBenchmarkResultsAsTable(data);
391 void runBenchmarks() {
392 CHECK(!benchmarks.empty());
394 vector<tuple<const char*, const char*, double>> results;
395 results.reserve(benchmarks.size() - 1);
397 // PLEASE KEEP QUIET. MEASUREMENTS IN PROGRESS.
399 auto const globalBaseline = runBenchmarkGetNSPerIteration(
400 get<2>(benchmarks.front()), 0);
401 FOR_EACH_RANGE (i, 1, benchmarks.size()) {
402 auto elapsed = strcmp(get<1>(benchmarks[i]), "-") == 0
403 ? 0.0 // skip the separators
404 : runBenchmarkGetNSPerIteration(get<2>(benchmarks[i]),
406 results.emplace_back(get<0>(benchmarks[i]),
407 get<1>(benchmarks[i]), elapsed);
410 // PLEASE MAKE NOISE. MEASUREMENTS DONE.
412 printBenchmarkResults(results);