ccae03448d064bebf3432e9e2f93ee9eeff4e5f8
[folly.git] / folly / Benchmark.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 // @author Andrei Alexandrescu (andrei.alexandrescu@fb.com)
18
19 #include <folly/Benchmark.h>
20 #include <folly/Foreach.h>
21 #include <folly/json.h>
22 #include <folly/String.h>
23
24 #include <algorithm>
25 #include <boost/regex.hpp>
26 #include <cmath>
27 #include <iostream>
28 #include <limits>
29 #include <utility>
30 #include <vector>
31 #include <cstring>
32
33 using namespace std;
34
35 DEFINE_bool(benchmark, false, "Run benchmarks.");
36 DEFINE_bool(json, false, "Output in JSON format.");
37
38 DEFINE_string(
39     bm_regex,
40     "",
41     "Only benchmarks whose names match this regex will be run.");
42
43 DEFINE_int64(
44     bm_min_usec,
45     100,
46     "Minimum # of microseconds we'll accept for each benchmark.");
47
48 DEFINE_int32(
49     bm_min_iters,
50     1,
51     "Minimum # of iterations we'll try for each benchmark.");
52
53 DEFINE_int64(
54     bm_max_iters,
55     1L << 30L,
56     "Maximum # of iterations we'll try for each benchmark.");
57
58 DEFINE_int32(
59     bm_max_secs,
60     1,
61     "Maximum # of seconds we'll spend on each benchmark.");
62
63 namespace folly {
64
65 BenchmarkSuspender::NanosecondsSpent BenchmarkSuspender::nsSpent;
66
67 typedef function<detail::TimeIterPair(unsigned int)> BenchmarkFun;
68
69
70 vector<tuple<string, string, BenchmarkFun>>& benchmarks() {
71   static vector<tuple<string, string, BenchmarkFun>> _benchmarks;
72   return _benchmarks;
73 }
74
75 #define FB_FOLLY_GLOBAL_BENCHMARK_BASELINE fbFollyGlobalBenchmarkBaseline
76 #define FB_STRINGIZE_X2(x) FB_STRINGIZE(x)
77
78 // Add the global baseline
79 BENCHMARK(FB_FOLLY_GLOBAL_BENCHMARK_BASELINE) {
80 #ifdef _MSC_VER
81   _ReadWriteBarrier();
82 #else
83   asm volatile("");
84 #endif
85 }
86
87 size_t getGlobalBenchmarkBaselineIndex() {
88   const char *global = FB_STRINGIZE_X2(FB_FOLLY_GLOBAL_BENCHMARK_BASELINE);
89   auto it = std::find_if(
90     benchmarks().begin(),
91     benchmarks().end(),
92     [global](const tuple<string, string, BenchmarkFun> &v) {
93       return get<1>(v) == global;
94     }
95   );
96   CHECK(it != benchmarks().end());
97   return size_t(std::distance(benchmarks().begin(), it));
98 }
99
100 #undef FB_STRINGIZE_X2
101 #undef FB_FOLLY_GLOBAL_BENCHMARK_BASELINE
102
103 void detail::addBenchmarkImpl(const char* file, const char* name,
104                               BenchmarkFun fun) {
105   benchmarks().emplace_back(file, name, std::move(fun));
106 }
107
108 /**
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.
113  */
114 static double density(const double * begin, const double *const end,
115                       const double where, const double bandwidth) {
116   assert(begin < end);
117   assert(bandwidth > 0.0);
118   double sum = 0.0;
119   FOR_EACH_RANGE (i, begin, end) {
120     auto d = (*i - where) / bandwidth;
121     sum += exp(- d * d);
122   }
123   return sum / (end - begin);
124 }
125
126 /**
127  * Computes mean and variance for a bunch of data points. Note that
128  * mean is currently not being used.
129  */
130 static pair<double, double>
131 meanVariance(const double * begin, const double *const end) {
132   assert(begin < end);
133   double sum = 0.0, sum2 = 0.0;
134   FOR_EACH_RANGE (i, begin, end) {
135     sum += *i;
136     sum2 += *i * *i;
137   }
138   auto const n = end - begin;
139   return make_pair(sum / n, sqrt((sum2 - sum * sum / n) / n));
140 }
141
142 /**
143  * Computes the mode of a sample set through brute force. Assumes
144  * input is sorted.
145  */
146 static double mode(const double * begin, const double *const end) {
147   assert(begin < end);
148   // Lower bound and upper bound for result and their respective
149   // densities.
150   auto
151     result = 0.0,
152     bestDensity = 0.0;
153
154   // Get the variance so we pass it down to density()
155   auto const sigma = meanVariance(begin, end).second;
156   if (!sigma) {
157     // No variance means constant signal
158     return *begin;
159   }
160
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) {
165       // Found a new best
166       bestDensity = candidate;
167       result = *i;
168     } else {
169       // Density is decreasing... we could break here if we definitely
170       // knew this is unimodal.
171     }
172   }
173
174   return result;
175 }
176
177 /**
178  * Given a bunch of benchmark samples, estimate the actual run time.
179  */
180 static double estimateTime(double * begin, double * end) {
181   assert(begin < end);
182
183   // Current state of the art: get the minimum. After some
184   // experimentation, it seems taking the minimum is the best.
185
186   return *min_element(begin, end);
187
188   // What follows after estimates the time as the mode of the
189   // distribution.
190
191   // Select the awesomest (i.e. most frequent) result. We do this by
192   // sorting and then computing the longest run length.
193   sort(begin, end);
194
195   // Eliminate outliers. A time much larger than the minimum time is
196   // considered an outlier.
197   while (end[-1] > 2.0 * *begin) {
198     --end;
199     if (begin == end) {
200       LOG(INFO) << *begin;
201     }
202     assert(begin < end);
203   }
204
205   double result = 0;
206
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;
217         }
218         if (current == end) {
219           break;
220         }
221         // Start a new run
222         candidateValue = *current;
223         candidateFrequency = 1;
224       } else {
225         // Cool, inside a run, increase the frequency
226         ++candidateFrequency;
227       }
228     }
229   }
230
231   result = mode(begin, end);
232
233   return result;
234 }
235
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
240   // timings.
241   static uint64_t resolutionInNs = 0;
242   if (!resolutionInNs) {
243     timespec ts;
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;
249   }
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));
256
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;
263   timespec global;
264   CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &global));
265
266   double epochResults[epochs] = { 0 };
267   size_t actualEpochs = 0;
268
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) {
274         continue;
275       }
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.
281       break;
282     }
283     timespec now;
284     CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &now));
285     if (detail::timespecDiff(now, global) >= timeBudgetInNs) {
286       // No more time budget available.
287       ++actualEpochs;
288       break;
289     }
290   }
291
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));
295 }
296
297 struct ScaleInfo {
298   double boundary;
299   const char* suffix;
300 };
301
302 static const ScaleInfo kTimeSuffixes[] {
303   { 365.25 * 24 * 3600, "years" },
304   { 24 * 3600, "days" },
305   { 3600, "hr" },
306   { 60, "min" },
307   { 1, "s" },
308   { 1E-3, "ms" },
309   { 1E-6, "us" },
310   { 1E-9, "ns" },
311   { 1E-12, "ps" },
312   { 1E-15, "fs" },
313   { 0, nullptr },
314 };
315
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
326   { 1, "" },
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
335   { 0, nullptr },
336 };
337
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);
342   }
343
344   const double absValue = fabs(n);
345   const ScaleInfo* scale = scales;
346   while (absValue < scale[0].boundary && scale[1].suffix != nullptr) {
347     ++scale;
348   }
349
350   const double scaledValue = n / scale->boundary;
351   return stringPrintf("%.*f%s", decimals, scaledValue, scale->suffix);
352 }
353
354 static string readableTime(double n, unsigned int decimals) {
355   return humanReadable(n, decimals, kTimeSuffixes);
356 }
357
358 static string metricReadable(double n, unsigned int decimals) {
359   return humanReadable(n, decimals, kMetricSuffixes);
360 }
361
362 static void printBenchmarkResultsAsTable(
363   const vector<tuple<string, string, double> >& data) {
364   // Width available
365   static const unsigned int columns = 76;
366
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());
371   }
372
373   // Print a horizontal rule
374   auto separator = [&](char pad) {
375     puts(string(columns, pad).c_str());
376   };
377
378   // Print header for a file
379   auto header = [&](const string& file) {
380     separator('=');
381     printf("%-*srelative  time/iter  iters/s\n",
382            columns - 28, file.c_str());
383     separator('=');
384   };
385
386   double baselineNsPerIter = numeric_limits<double>::max();
387   string lastFile;
388
389   for (auto& datum : data) {
390     auto file = get<0>(datum);
391     if (file != lastFile) {
392       // New file starting
393       header(file);
394       lastFile = file;
395     }
396
397     string s = get<1>(datum);
398     if (s == "-") {
399       separator('-');
400       continue;
401     }
402     bool useBaseline /* = void */;
403     if (s[0] == '%') {
404       s.erase(0, 1);
405       useBaseline = true;
406     } else {
407       baselineNsPerIter = get<2>(datum);
408       useBaseline = false;
409     }
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()
415                            : (1 / secPerIter);
416     if (!useBaseline) {
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());
422     } else {
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(),
427              rel,
428              readableTime(secPerIter, 2).c_str(),
429              metricReadable(itersPerSec, 2).c_str());
430     }
431   }
432   separator('=');
433 }
434
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.;
440   }
441
442   printf("%s\n", toPrettyJson(d).c_str());
443 }
444
445 static void printBenchmarkResults(
446   const vector<tuple<string, string, double> >& data) {
447
448   if (FLAGS_json) {
449     printBenchmarkResultsAsJson(data);
450   } else {
451     printBenchmarkResultsAsTable(data);
452   }
453 }
454
455 void runBenchmarks() {
456   CHECK(!benchmarks().empty());
457
458   vector<tuple<string, string, double>> results;
459   results.reserve(benchmarks().size() - 1);
460
461   std::unique_ptr<boost::regex> bmRegex;
462   if (!FLAGS_bm_regex.empty()) {
463     bmRegex.reset(new boost::regex(FLAGS_bm_regex));
464   }
465
466   // PLEASE KEEP QUIET. MEASUREMENTS IN PROGRESS.
467
468   size_t baselineIndex = getGlobalBenchmarkBaselineIndex();
469
470   auto const globalBaseline =
471       runBenchmarkGetNSPerIteration(get<2>(benchmarks()[baselineIndex]), 0);
472   FOR_EACH_RANGE (i, 0, benchmarks().size()) {
473     if (i == baselineIndex) {
474       continue;
475     }
476     double elapsed = 0.0;
477     if (get<1>(benchmarks()[i]) != "-") { // skip separators
478       if (bmRegex && !boost::regex_search(get<1>(benchmarks()[i]), *bmRegex)) {
479         continue;
480       }
481       elapsed = runBenchmarkGetNSPerIteration(get<2>(benchmarks()[i]),
482                                               globalBaseline);
483     }
484     results.emplace_back(get<0>(benchmarks()[i]),
485                          get<1>(benchmarks()[i]), elapsed);
486   }
487
488   // PLEASE MAKE NOISE. MEASUREMENTS DONE.
489
490   printBenchmarkResults(results);
491 }
492
493 } // namespace folly