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 bunch of benchmark samples, estimate the actual run time.
110  */
111 static double estimateTime(double * begin, double * end) {
112   assert(begin < end);
113
114   // Current state of the art: get the minimum. After some
115   // experimentation, it seems taking the minimum is the best.
116   return *min_element(begin, end);
117 }
118
119 static double runBenchmarkGetNSPerIteration(const BenchmarkFun& fun,
120                                             const double globalBaseline) {
121   // They key here is accuracy; too low numbers means the accuracy was
122   // coarse. We up the ante until we get to at least minNanoseconds
123   // timings.
124   static uint64_t resolutionInNs = 0;
125   if (!resolutionInNs) {
126     timespec ts;
127     CHECK_EQ(0, clock_getres(CLOCK_REALTIME, &ts));
128     CHECK_EQ(0, ts.tv_sec) << "Clock sucks.";
129     CHECK_LT(0, ts.tv_nsec) << "Clock too fast for its own good.";
130     CHECK_EQ(1, ts.tv_nsec) << "Clock too coarse, upgrade your kernel.";
131     resolutionInNs = ts.tv_nsec;
132   }
133   // We choose a minimum minimum (sic) of 100,000 nanoseconds, but if
134   // the clock resolution is worse than that, it will be larger. In
135   // essence we're aiming at making the quantization noise 0.01%.
136   static const auto minNanoseconds =
137     max<uint64_t>(FLAGS_bm_min_usec * 1000UL,
138         min<uint64_t>(resolutionInNs * 100000, 1000000000ULL));
139
140   // We do measurements in several epochs and take the minimum, to
141   // account for jitter.
142   static const unsigned int epochs = 1000;
143   // We establish a total time budget as we don't want a measurement
144   // to take too long. This will curtail the number of actual epochs.
145   const uint64_t timeBudgetInNs = FLAGS_bm_max_secs * 1000000000ULL;
146   timespec global;
147   CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &global));
148
149   double epochResults[epochs] = { 0 };
150   size_t actualEpochs = 0;
151
152   for (; actualEpochs < epochs; ++actualEpochs) {
153     const auto maxIters = FLAGS_bm_max_iters;
154     for (unsigned int n = FLAGS_bm_min_iters; n < maxIters; n *= 2) {
155       auto const nsecsAndIter = fun(n);
156       if (nsecsAndIter.first < minNanoseconds) {
157         continue;
158       }
159       // We got an accurate enough timing, done. But only save if
160       // smaller than the current result.
161       epochResults[actualEpochs] = max(0.0, double(nsecsAndIter.first) /
162                                        nsecsAndIter.second - globalBaseline);
163       // Done with the current epoch, we got a meaningful timing.
164       break;
165     }
166     timespec now;
167     CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &now));
168     if (detail::timespecDiff(now, global) >= timeBudgetInNs) {
169       // No more time budget available.
170       ++actualEpochs;
171       break;
172     }
173   }
174
175   // If the benchmark was basically drowned in baseline noise, it's
176   // possible it became negative.
177   return max(0.0, estimateTime(epochResults, epochResults + actualEpochs));
178 }
179
180 struct ScaleInfo {
181   double boundary;
182   const char* suffix;
183 };
184
185 static const ScaleInfo kTimeSuffixes[] {
186   { 365.25 * 24 * 3600, "years" },
187   { 24 * 3600, "days" },
188   { 3600, "hr" },
189   { 60, "min" },
190   { 1, "s" },
191   { 1E-3, "ms" },
192   { 1E-6, "us" },
193   { 1E-9, "ns" },
194   { 1E-12, "ps" },
195   { 1E-15, "fs" },
196   { 0, nullptr },
197 };
198
199 static const ScaleInfo kMetricSuffixes[] {
200   { 1E24, "Y" },  // yotta
201   { 1E21, "Z" },  // zetta
202   { 1E18, "X" },  // "exa" written with suffix 'X' so as to not create
203                   //   confusion with scientific notation
204   { 1E15, "P" },  // peta
205   { 1E12, "T" },  // terra
206   { 1E9, "G" },   // giga
207   { 1E6, "M" },   // mega
208   { 1E3, "K" },   // kilo
209   { 1, "" },
210   { 1E-3, "m" },  // milli
211   { 1E-6, "u" },  // micro
212   { 1E-9, "n" },  // nano
213   { 1E-12, "p" }, // pico
214   { 1E-15, "f" }, // femto
215   { 1E-18, "a" }, // atto
216   { 1E-21, "z" }, // zepto
217   { 1E-24, "y" }, // yocto
218   { 0, nullptr },
219 };
220
221 static string humanReadable(double n, unsigned int decimals,
222                             const ScaleInfo* scales) {
223   if (std::isinf(n) || std::isnan(n)) {
224     return folly::to<string>(n);
225   }
226
227   const double absValue = fabs(n);
228   const ScaleInfo* scale = scales;
229   while (absValue < scale[0].boundary && scale[1].suffix != nullptr) {
230     ++scale;
231   }
232
233   const double scaledValue = n / scale->boundary;
234   return stringPrintf("%.*f%s", decimals, scaledValue, scale->suffix);
235 }
236
237 static string readableTime(double n, unsigned int decimals) {
238   return humanReadable(n, decimals, kTimeSuffixes);
239 }
240
241 static string metricReadable(double n, unsigned int decimals) {
242   return humanReadable(n, decimals, kMetricSuffixes);
243 }
244
245 static void printBenchmarkResultsAsTable(
246   const vector<tuple<string, string, double> >& data) {
247   // Width available
248   static const unsigned int columns = 76;
249
250   // Compute the longest benchmark name
251   size_t longestName = 0;
252   FOR_EACH_RANGE (i, 1, benchmarks().size()) {
253     longestName = max(longestName, get<1>(benchmarks()[i]).size());
254   }
255
256   // Print a horizontal rule
257   auto separator = [&](char pad) {
258     puts(string(columns, pad).c_str());
259   };
260
261   // Print header for a file
262   auto header = [&](const string& file) {
263     separator('=');
264     printf("%-*srelative  time/iter  iters/s\n",
265            columns - 28, file.c_str());
266     separator('=');
267   };
268
269   double baselineNsPerIter = numeric_limits<double>::max();
270   string lastFile;
271
272   for (auto& datum : data) {
273     auto file = get<0>(datum);
274     if (file != lastFile) {
275       // New file starting
276       header(file);
277       lastFile = file;
278     }
279
280     string s = get<1>(datum);
281     if (s == "-") {
282       separator('-');
283       continue;
284     }
285     bool useBaseline /* = void */;
286     if (s[0] == '%') {
287       s.erase(0, 1);
288       useBaseline = true;
289     } else {
290       baselineNsPerIter = get<2>(datum);
291       useBaseline = false;
292     }
293     s.resize(columns - 29, ' ');
294     auto nsPerIter = get<2>(datum);
295     auto secPerIter = nsPerIter / 1E9;
296     auto itersPerSec = (secPerIter == 0)
297                            ? std::numeric_limits<double>::infinity()
298                            : (1 / secPerIter);
299     if (!useBaseline) {
300       // Print without baseline
301       printf("%*s           %9s  %7s\n",
302              static_cast<int>(s.size()), s.c_str(),
303              readableTime(secPerIter, 2).c_str(),
304              metricReadable(itersPerSec, 2).c_str());
305     } else {
306       // Print with baseline
307       auto rel = baselineNsPerIter / nsPerIter * 100.0;
308       printf("%*s %7.2f%%  %9s  %7s\n",
309              static_cast<int>(s.size()), s.c_str(),
310              rel,
311              readableTime(secPerIter, 2).c_str(),
312              metricReadable(itersPerSec, 2).c_str());
313     }
314   }
315   separator('=');
316 }
317
318 static void printBenchmarkResultsAsJson(
319   const vector<tuple<string, string, double> >& data) {
320   dynamic d = dynamic::object;
321   for (auto& datum: data) {
322     d[std::get<1>(datum)] = std::get<2>(datum) * 1000.;
323   }
324
325   printf("%s\n", toPrettyJson(d).c_str());
326 }
327
328 static void printBenchmarkResults(
329   const vector<tuple<string, string, double> >& data) {
330
331   if (FLAGS_json) {
332     printBenchmarkResultsAsJson(data);
333   } else {
334     printBenchmarkResultsAsTable(data);
335   }
336 }
337
338 void runBenchmarks() {
339   CHECK(!benchmarks().empty());
340
341   vector<tuple<string, string, double>> results;
342   results.reserve(benchmarks().size() - 1);
343
344   std::unique_ptr<boost::regex> bmRegex;
345   if (!FLAGS_bm_regex.empty()) {
346     bmRegex.reset(new boost::regex(FLAGS_bm_regex));
347   }
348
349   // PLEASE KEEP QUIET. MEASUREMENTS IN PROGRESS.
350
351   size_t baselineIndex = getGlobalBenchmarkBaselineIndex();
352
353   auto const globalBaseline =
354       runBenchmarkGetNSPerIteration(get<2>(benchmarks()[baselineIndex]), 0);
355   FOR_EACH_RANGE (i, 0, benchmarks().size()) {
356     if (i == baselineIndex) {
357       continue;
358     }
359     double elapsed = 0.0;
360     if (get<1>(benchmarks()[i]) != "-") { // skip separators
361       if (bmRegex && !boost::regex_search(get<1>(benchmarks()[i]), *bmRegex)) {
362         continue;
363       }
364       elapsed = runBenchmarkGetNSPerIteration(get<2>(benchmarks()[i]),
365                                               globalBaseline);
366     }
367     results.emplace_back(get<0>(benchmarks()[i]),
368                          get<1>(benchmarks()[i]), elapsed);
369   }
370
371   // PLEASE MAKE NOISE. MEASUREMENTS DONE.
372
373   printBenchmarkResults(results);
374 }
375
376 } // namespace folly