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 size_t 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 size_t(std::distance(benchmarks().begin(), it));
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 * Given a bunch of benchmark samples, estimate the actual run time.
145 static double estimateTime(double * begin, double * end) {
148 // Current state of the art: get the minimum. After some
149 // experimentation, it seems taking the minimum is the best.
150 return *min_element(begin, end);
153 static double runBenchmarkGetNSPerIteration(const BenchmarkFun& fun,
154 const double globalBaseline) {
155 // They key here is accuracy; too low numbers means the accuracy was
156 // coarse. We up the ante until we get to at least minNanoseconds
158 static uint64_t resolutionInNs = 0;
159 if (!resolutionInNs) {
161 CHECK_EQ(0, clock_getres(CLOCK_REALTIME, &ts));
162 CHECK_EQ(0, ts.tv_sec) << "Clock sucks.";
163 CHECK_LT(0, ts.tv_nsec) << "Clock too fast for its own good.";
164 CHECK_EQ(1, ts.tv_nsec) << "Clock too coarse, upgrade your kernel.";
165 resolutionInNs = ts.tv_nsec;
167 // We choose a minimum minimum (sic) of 100,000 nanoseconds, but if
168 // the clock resolution is worse than that, it will be larger. In
169 // essence we're aiming at making the quantization noise 0.01%.
170 static const auto minNanoseconds =
171 max<uint64_t>(FLAGS_bm_min_usec * 1000UL,
172 min<uint64_t>(resolutionInNs * 100000, 1000000000ULL));
174 // We do measurements in several epochs and take the minimum, to
175 // account for jitter.
176 static const unsigned int epochs = 1000;
177 // We establish a total time budget as we don't want a measurement
178 // to take too long. This will curtail the number of actual epochs.
179 const uint64_t timeBudgetInNs = FLAGS_bm_max_secs * 1000000000ULL;
181 CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &global));
183 double epochResults[epochs] = { 0 };
184 size_t actualEpochs = 0;
186 for (; actualEpochs < epochs; ++actualEpochs) {
187 const auto maxIters = FLAGS_bm_max_iters;
188 for (unsigned int n = FLAGS_bm_min_iters; n < maxIters; n *= 2) {
189 auto const nsecsAndIter = fun(n);
190 if (nsecsAndIter.first < minNanoseconds) {
193 // We got an accurate enough timing, done. But only save if
194 // smaller than the current result.
195 epochResults[actualEpochs] = max(0.0, double(nsecsAndIter.first) /
196 nsecsAndIter.second - globalBaseline);
197 // Done with the current epoch, we got a meaningful timing.
201 CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &now));
202 if (detail::timespecDiff(now, global) >= timeBudgetInNs) {
203 // No more time budget available.
209 // If the benchmark was basically drowned in baseline noise, it's
210 // possible it became negative.
211 return max(0.0, estimateTime(epochResults, epochResults + actualEpochs));
219 static const ScaleInfo kTimeSuffixes[] {
220 { 365.25 * 24 * 3600, "years" },
221 { 24 * 3600, "days" },
233 static const ScaleInfo kMetricSuffixes[] {
234 { 1E24, "Y" }, // yotta
235 { 1E21, "Z" }, // zetta
236 { 1E18, "X" }, // "exa" written with suffix 'X' so as to not create
237 // confusion with scientific notation
238 { 1E15, "P" }, // peta
239 { 1E12, "T" }, // terra
240 { 1E9, "G" }, // giga
241 { 1E6, "M" }, // mega
242 { 1E3, "K" }, // kilo
244 { 1E-3, "m" }, // milli
245 { 1E-6, "u" }, // micro
246 { 1E-9, "n" }, // nano
247 { 1E-12, "p" }, // pico
248 { 1E-15, "f" }, // femto
249 { 1E-18, "a" }, // atto
250 { 1E-21, "z" }, // zepto
251 { 1E-24, "y" }, // yocto
255 static string humanReadable(double n, unsigned int decimals,
256 const ScaleInfo* scales) {
257 if (std::isinf(n) || std::isnan(n)) {
258 return folly::to<string>(n);
261 const double absValue = fabs(n);
262 const ScaleInfo* scale = scales;
263 while (absValue < scale[0].boundary && scale[1].suffix != nullptr) {
267 const double scaledValue = n / scale->boundary;
268 return stringPrintf("%.*f%s", decimals, scaledValue, scale->suffix);
271 static string readableTime(double n, unsigned int decimals) {
272 return humanReadable(n, decimals, kTimeSuffixes);
275 static string metricReadable(double n, unsigned int decimals) {
276 return humanReadable(n, decimals, kMetricSuffixes);
279 static void printBenchmarkResultsAsTable(
280 const vector<tuple<string, string, double> >& data) {
282 static const unsigned int columns = 76;
284 // Compute the longest benchmark name
285 size_t longestName = 0;
286 FOR_EACH_RANGE (i, 1, benchmarks().size()) {
287 longestName = max(longestName, get<1>(benchmarks()[i]).size());
290 // Print a horizontal rule
291 auto separator = [&](char pad) {
292 puts(string(columns, pad).c_str());
295 // Print header for a file
296 auto header = [&](const string& file) {
298 printf("%-*srelative time/iter iters/s\n",
299 columns - 28, file.c_str());
303 double baselineNsPerIter = numeric_limits<double>::max();
306 for (auto& datum : data) {
307 auto file = get<0>(datum);
308 if (file != lastFile) {
314 string s = get<1>(datum);
319 bool useBaseline /* = void */;
324 baselineNsPerIter = get<2>(datum);
327 s.resize(columns - 29, ' ');
328 auto nsPerIter = get<2>(datum);
329 auto secPerIter = nsPerIter / 1E9;
330 auto itersPerSec = (secPerIter == 0)
331 ? std::numeric_limits<double>::infinity()
334 // Print without baseline
335 printf("%*s %9s %7s\n",
336 static_cast<int>(s.size()), s.c_str(),
337 readableTime(secPerIter, 2).c_str(),
338 metricReadable(itersPerSec, 2).c_str());
340 // Print with baseline
341 auto rel = baselineNsPerIter / nsPerIter * 100.0;
342 printf("%*s %7.2f%% %9s %7s\n",
343 static_cast<int>(s.size()), s.c_str(),
345 readableTime(secPerIter, 2).c_str(),
346 metricReadable(itersPerSec, 2).c_str());
352 static void printBenchmarkResultsAsJson(
353 const vector<tuple<string, string, double> >& data) {
354 dynamic d = dynamic::object;
355 for (auto& datum: data) {
356 d[std::get<1>(datum)] = std::get<2>(datum) * 1000.;
359 printf("%s\n", toPrettyJson(d).c_str());
362 static void printBenchmarkResults(
363 const vector<tuple<string, string, double> >& data) {
366 printBenchmarkResultsAsJson(data);
368 printBenchmarkResultsAsTable(data);
372 void runBenchmarks() {
373 CHECK(!benchmarks().empty());
375 vector<tuple<string, string, double>> results;
376 results.reserve(benchmarks().size() - 1);
378 std::unique_ptr<boost::regex> bmRegex;
379 if (!FLAGS_bm_regex.empty()) {
380 bmRegex.reset(new boost::regex(FLAGS_bm_regex));
383 // PLEASE KEEP QUIET. MEASUREMENTS IN PROGRESS.
385 size_t baselineIndex = getGlobalBenchmarkBaselineIndex();
387 auto const globalBaseline =
388 runBenchmarkGetNSPerIteration(get<2>(benchmarks()[baselineIndex]), 0);
389 FOR_EACH_RANGE (i, 0, benchmarks().size()) {
390 if (i == baselineIndex) {
393 double elapsed = 0.0;
394 if (get<1>(benchmarks()[i]) != "-") { // skip separators
395 if (bmRegex && !boost::regex_search(get<1>(benchmarks()[i]), *bmRegex)) {
398 elapsed = runBenchmarkGetNSPerIteration(get<2>(benchmarks()[i]),
401 results.emplace_back(get<0>(benchmarks()[i]),
402 get<1>(benchmarks()[i]), elapsed);
405 // PLEASE MAKE NOISE. MEASUREMENTS DONE.
407 printBenchmarkResults(results);