Enable -Wunreachable-code
[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  * Given a bunch of benchmark samples, estimate the actual run time.
144  */
145 static double estimateTime(double * begin, double * end) {
146   assert(begin < end);
147
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);
151 }
152
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
157   // timings.
158   static uint64_t resolutionInNs = 0;
159   if (!resolutionInNs) {
160     timespec ts;
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;
166   }
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));
173
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;
180   timespec global;
181   CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &global));
182
183   double epochResults[epochs] = { 0 };
184   size_t actualEpochs = 0;
185
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) {
191         continue;
192       }
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.
198       break;
199     }
200     timespec now;
201     CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &now));
202     if (detail::timespecDiff(now, global) >= timeBudgetInNs) {
203       // No more time budget available.
204       ++actualEpochs;
205       break;
206     }
207   }
208
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));
212 }
213
214 struct ScaleInfo {
215   double boundary;
216   const char* suffix;
217 };
218
219 static const ScaleInfo kTimeSuffixes[] {
220   { 365.25 * 24 * 3600, "years" },
221   { 24 * 3600, "days" },
222   { 3600, "hr" },
223   { 60, "min" },
224   { 1, "s" },
225   { 1E-3, "ms" },
226   { 1E-6, "us" },
227   { 1E-9, "ns" },
228   { 1E-12, "ps" },
229   { 1E-15, "fs" },
230   { 0, nullptr },
231 };
232
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
243   { 1, "" },
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
252   { 0, nullptr },
253 };
254
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);
259   }
260
261   const double absValue = fabs(n);
262   const ScaleInfo* scale = scales;
263   while (absValue < scale[0].boundary && scale[1].suffix != nullptr) {
264     ++scale;
265   }
266
267   const double scaledValue = n / scale->boundary;
268   return stringPrintf("%.*f%s", decimals, scaledValue, scale->suffix);
269 }
270
271 static string readableTime(double n, unsigned int decimals) {
272   return humanReadable(n, decimals, kTimeSuffixes);
273 }
274
275 static string metricReadable(double n, unsigned int decimals) {
276   return humanReadable(n, decimals, kMetricSuffixes);
277 }
278
279 static void printBenchmarkResultsAsTable(
280   const vector<tuple<string, string, double> >& data) {
281   // Width available
282   static const unsigned int columns = 76;
283
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());
288   }
289
290   // Print a horizontal rule
291   auto separator = [&](char pad) {
292     puts(string(columns, pad).c_str());
293   };
294
295   // Print header for a file
296   auto header = [&](const string& file) {
297     separator('=');
298     printf("%-*srelative  time/iter  iters/s\n",
299            columns - 28, file.c_str());
300     separator('=');
301   };
302
303   double baselineNsPerIter = numeric_limits<double>::max();
304   string lastFile;
305
306   for (auto& datum : data) {
307     auto file = get<0>(datum);
308     if (file != lastFile) {
309       // New file starting
310       header(file);
311       lastFile = file;
312     }
313
314     string s = get<1>(datum);
315     if (s == "-") {
316       separator('-');
317       continue;
318     }
319     bool useBaseline /* = void */;
320     if (s[0] == '%') {
321       s.erase(0, 1);
322       useBaseline = true;
323     } else {
324       baselineNsPerIter = get<2>(datum);
325       useBaseline = false;
326     }
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()
332                            : (1 / secPerIter);
333     if (!useBaseline) {
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());
339     } else {
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(),
344              rel,
345              readableTime(secPerIter, 2).c_str(),
346              metricReadable(itersPerSec, 2).c_str());
347     }
348   }
349   separator('=');
350 }
351
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.;
357   }
358
359   printf("%s\n", toPrettyJson(d).c_str());
360 }
361
362 static void printBenchmarkResults(
363   const vector<tuple<string, string, double> >& data) {
364
365   if (FLAGS_json) {
366     printBenchmarkResultsAsJson(data);
367   } else {
368     printBenchmarkResultsAsTable(data);
369   }
370 }
371
372 void runBenchmarks() {
373   CHECK(!benchmarks().empty());
374
375   vector<tuple<string, string, double>> results;
376   results.reserve(benchmarks().size() - 1);
377
378   std::unique_ptr<boost::regex> bmRegex;
379   if (!FLAGS_bm_regex.empty()) {
380     bmRegex.reset(new boost::regex(FLAGS_bm_regex));
381   }
382
383   // PLEASE KEEP QUIET. MEASUREMENTS IN PROGRESS.
384
385   size_t baselineIndex = getGlobalBenchmarkBaselineIndex();
386
387   auto const globalBaseline =
388       runBenchmarkGetNSPerIteration(get<2>(benchmarks()[baselineIndex]), 0);
389   FOR_EACH_RANGE (i, 0, benchmarks().size()) {
390     if (i == baselineIndex) {
391       continue;
392     }
393     double elapsed = 0.0;
394     if (get<1>(benchmarks()[i]) != "-") { // skip separators
395       if (bmRegex && !boost::regex_search(get<1>(benchmarks()[i]), *bmRegex)) {
396         continue;
397       }
398       elapsed = runBenchmarkGetNSPerIteration(get<2>(benchmarks()[i]),
399                                               globalBaseline);
400     }
401     results.emplace_back(get<0>(benchmarks()[i]),
402                          get<1>(benchmarks()[i]), elapsed);
403   }
404
405   // PLEASE MAKE NOISE. MEASUREMENTS DONE.
406
407   printBenchmarkResults(results);
408 }
409
410 } // namespace folly