revert folly/Benchmark.cpp
[folly.git] / folly / Benchmark.cpp
1 /*
2  * Copyright 2013 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 "Benchmark.h"
20 #include "Foreach.h"
21 #include "json.h"
22 #include "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
32 using namespace std;
33
34 DEFINE_bool(benchmark, false, "Run benchmarks.");
35 DEFINE_bool(json, false, "Output in JSON format.");
36
37 DEFINE_string(bm_regex, "",
38               "Only benchmarks whose names match this regex will be run.");
39
40 DEFINE_int64(bm_min_usec, 100,
41              "Minimum # of microseconds we'll accept for each benchmark.");
42
43 DEFINE_int64(bm_min_iters, 1,
44              "Minimum # of iterations we'll try for each benchmark.");
45
46 DEFINE_int32(bm_max_secs, 1,
47              "Maximum # of seconds we'll spend on each benchmark.");
48
49
50 namespace folly {
51
52 BenchmarkSuspender::NanosecondsSpent BenchmarkSuspender::nsSpent;
53
54 typedef function<uint64_t(unsigned int)> BenchmarkFun;
55 static vector<tuple<const char*, const char*, BenchmarkFun>> benchmarks;
56
57 // Add the global baseline
58 BENCHMARK(globalBenchmarkBaseline) {
59   asm volatile("");
60 }
61
62 void detail::addBenchmarkImpl(const char* file, const char* name,
63                               BenchmarkFun fun) {
64   benchmarks.emplace_back(file, name, std::move(fun));
65 }
66
67 /**
68  * Given a point, gives density at that point as a number 0.0 < x <=
69  * 1.0. The result is 1.0 if all samples are equal to where, and
70  * decreases near 0 if all points are far away from it. The density is
71  * computed with the help of a radial basis function.
72  */
73 static double density(const double * begin, const double *const end,
74                       const double where, const double bandwidth) {
75   assert(begin < end);
76   assert(bandwidth > 0.0);
77   double sum = 0.0;
78   FOR_EACH_RANGE (i, begin, end) {
79     auto d = (*i - where) / bandwidth;
80     sum += exp(- d * d);
81   }
82   return sum / (end - begin);
83 }
84
85 /**
86  * Computes mean and variance for a bunch of data points. Note that
87  * mean is currently not being used.
88  */
89 static pair<double, double>
90 meanVariance(const double * begin, const double *const end) {
91   assert(begin < end);
92   double sum = 0.0, sum2 = 0.0;
93   FOR_EACH_RANGE (i, begin, end) {
94     sum += *i;
95     sum2 += *i * *i;
96   }
97   auto const n = end - begin;
98   return make_pair(sum / n, sqrt((sum2 - sum * sum / n) / n));
99 }
100
101 /**
102  * Computes the mode of a sample set through brute force. Assumes
103  * input is sorted.
104  */
105 static double mode(const double * begin, const double *const end) {
106   assert(begin < end);
107   // Lower bound and upper bound for result and their respective
108   // densities.
109   auto
110     result = 0.0,
111     bestDensity = 0.0;
112
113   // Get the variance so we pass it down to density()
114   auto const sigma = meanVariance(begin, end).second;
115   if (!sigma) {
116     // No variance means constant signal
117     return *begin;
118   }
119
120   FOR_EACH_RANGE (i, begin, end) {
121     assert(i == begin || *i >= i[-1]);
122     auto candidate = density(begin, end, *i, sigma * sqrt(2.0));
123     if (candidate > bestDensity) {
124       // Found a new best
125       bestDensity = candidate;
126       result = *i;
127     } else {
128       // Density is decreasing... we could break here if we definitely
129       // knew this is unimodal.
130     }
131   }
132
133   return result;
134 }
135
136 /**
137  * Given a bunch of benchmark samples, estimate the actual run time.
138  */
139 static double estimateTime(double * begin, double * end) {
140   assert(begin < end);
141
142   // Current state of the art: get the minimum. After some
143   // experimentation, it seems taking the minimum is the best.
144
145   return *min_element(begin, end);
146
147   // What follows after estimates the time as the mode of the
148   // distribution.
149
150   // Select the awesomest (i.e. most frequent) result. We do this by
151   // sorting and then computing the longest run length.
152   sort(begin, end);
153
154   // Eliminate outliers. A time much larger than the minimum time is
155   // considered an outlier.
156   while (end[-1] > 2.0 * *begin) {
157     --end;
158     if (begin == end) {
159       LOG(INFO) << *begin;
160     }
161     assert(begin < end);
162   }
163
164   double result = 0;
165
166   /* Code used just for comparison purposes */ {
167     unsigned bestFrequency = 0;
168     unsigned candidateFrequency = 1;
169     double candidateValue = *begin;
170     for (auto current = begin + 1; ; ++current) {
171       if (current == end || *current != candidateValue) {
172         // Done with the current run, see if it was best
173         if (candidateFrequency > bestFrequency) {
174           bestFrequency = candidateFrequency;
175           result = candidateValue;
176         }
177         if (current == end) {
178           break;
179         }
180         // Start a new run
181         candidateValue = *current;
182         candidateFrequency = 1;
183       } else {
184         // Cool, inside a run, increase the frequency
185         ++candidateFrequency;
186       }
187     }
188   }
189
190   result = mode(begin, end);
191
192   return result;
193 }
194
195 static double runBenchmarkGetNSPerIteration(const BenchmarkFun& fun,
196                                             const double globalBaseline) {
197   // They key here is accuracy; too low numbers means the accuracy was
198   // coarse. We up the ante until we get to at least minNanoseconds
199   // timings.
200   static uint64_t resolutionInNs = 0, coarseResolutionInNs = 0;
201   if (!resolutionInNs) {
202     timespec ts;
203     CHECK_EQ(0, clock_getres(detail::DEFAULT_CLOCK_ID, &ts));
204     CHECK_EQ(0, ts.tv_sec) << "Clock sucks.";
205     CHECK_LT(0, ts.tv_nsec) << "Clock too fast for its own good.";
206     CHECK_EQ(1, ts.tv_nsec) << "Clock too coarse, upgrade your kernel.";
207     resolutionInNs = ts.tv_nsec;
208   }
209   // We choose a minimum minimum (sic) of 100,000 nanoseconds, but if
210   // the clock resolution is worse than that, it will be larger. In
211   // essence we're aiming at making the quantization noise 0.01%.
212   static const auto minNanoseconds =
213     max(FLAGS_bm_min_usec * 1000UL, min(resolutionInNs * 100000, 1000000000UL));
214
215   // We do measurements in several epochs and take the minimum, to
216   // account for jitter.
217   static const unsigned int epochs = 1000;
218   // We establish a total time budget as we don't want a measurement
219   // to take too long. This will curtail the number of actual epochs.
220   const uint64_t timeBudgetInNs = FLAGS_bm_max_secs * 1000000000;
221   timespec global;
222   CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &global));
223
224   double epochResults[epochs] = { 0 };
225   size_t actualEpochs = 0;
226
227   for (; actualEpochs < epochs; ++actualEpochs) {
228     for (unsigned int n = FLAGS_bm_min_iters; n < (1UL << 30); n *= 2) {
229       auto const nsecs = fun(n);
230       if (nsecs < minNanoseconds) {
231         continue;
232       }
233       // We got an accurate enough timing, done. But only save if
234       // smaller than the current result.
235       epochResults[actualEpochs] = max(0.0, double(nsecs) / n - globalBaseline);
236       // Done with the current epoch, we got a meaningful timing.
237       break;
238     }
239     timespec now;
240     CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &now));
241     if (detail::timespecDiff(now, global) >= timeBudgetInNs) {
242       // No more time budget available.
243       ++actualEpochs;
244       break;
245     }
246   }
247
248   // If the benchmark was basically drowned in baseline noise, it's
249   // possible it became negative.
250   return max(0.0, estimateTime(epochResults, epochResults + actualEpochs));
251 }
252
253 struct ScaleInfo {
254   double boundary;
255   const char* suffix;
256 };
257
258 static const ScaleInfo kTimeSuffixes[] {
259   { 365.25 * 24 * 3600, "years" },
260   { 24 * 3600, "days" },
261   { 3600, "hr" },
262   { 60, "min" },
263   { 1, "s" },
264   { 1E-3, "ms" },
265   { 1E-6, "us" },
266   { 1E-9, "ns" },
267   { 1E-12, "ps" },
268   { 1E-15, "fs" },
269   { 0, NULL },
270 };
271
272 static const ScaleInfo kMetricSuffixes[] {
273   { 1E24, "Y" },  // yotta
274   { 1E21, "Z" },  // zetta
275   { 1E18, "X" },  // "exa" written with suffix 'X' so as to not create
276                   //   confusion with scientific notation
277   { 1E15, "P" },  // peta
278   { 1E12, "T" },  // terra
279   { 1E9, "G" },   // giga
280   { 1E6, "M" },   // mega
281   { 1E3, "K" },   // kilo
282   { 1, "" },
283   { 1E-3, "m" },  // milli
284   { 1E-6, "u" },  // micro
285   { 1E-9, "n" },  // nano
286   { 1E-12, "p" }, // pico
287   { 1E-15, "f" }, // femto
288   { 1E-18, "a" }, // atto
289   { 1E-21, "z" }, // zepto
290   { 1E-24, "y" }, // yocto
291   { 0, NULL },
292 };
293
294 static string humanReadable(double n, unsigned int decimals,
295                             const ScaleInfo* scales) {
296   if (std::isinf(n) || std::isnan(n)) {
297     return folly::to<string>(n);
298   }
299
300   const double absValue = fabs(n);
301   const ScaleInfo* scale = scales;
302   while (absValue < scale[0].boundary && scale[1].suffix != NULL) {
303     ++scale;
304   }
305
306   const double scaledValue = n / scale->boundary;
307   return stringPrintf("%.*f%s", decimals, scaledValue, scale->suffix);
308 }
309
310 static string readableTime(double n, unsigned int decimals) {
311   return humanReadable(n, decimals, kTimeSuffixes);
312 }
313
314 static string metricReadable(double n, unsigned int decimals) {
315   return humanReadable(n, decimals, kMetricSuffixes);
316 }
317
318 static void printBenchmarkResultsAsTable(
319   const vector<tuple<const char*, const char*, double> >& data) {
320   // Width available
321   static const uint columns = 76;
322
323   // Compute the longest benchmark name
324   size_t longestName = 0;
325   FOR_EACH_RANGE (i, 1, benchmarks.size()) {
326     longestName = max(longestName, strlen(get<1>(benchmarks[i])));
327   }
328
329   // Print a horizontal rule
330   auto separator = [&](char pad) {
331     puts(string(columns, pad).c_str());
332   };
333
334   // Print header for a file
335   auto header = [&](const char* file) {
336     separator('=');
337     printf("%-*srelative  time/iter  iters/s\n",
338            columns - 28, file);
339     separator('=');
340   };
341
342   double baselineNsPerIter = numeric_limits<double>::max();
343   const char* lastFile = "";
344
345   for (auto& datum : data) {
346     auto file = get<0>(datum);
347     if (strcmp(file, lastFile)) {
348       // New file starting
349       header(file);
350       lastFile = file;
351     }
352
353     string s = get<1>(datum);
354     if (s == "-") {
355       separator('-');
356       continue;
357     }
358     bool useBaseline /* = void */;
359     if (s[0] == '%') {
360       s.erase(0, 1);
361       useBaseline = true;
362     } else {
363       baselineNsPerIter = get<2>(datum);
364       useBaseline = false;
365     }
366     s.resize(columns - 29, ' ');
367     auto nsPerIter = get<2>(datum);
368     auto secPerIter = nsPerIter / 1E9;
369     auto itersPerSec = 1 / secPerIter;
370     if (!useBaseline) {
371       // Print without baseline
372       printf("%*s           %9s  %7s\n",
373              static_cast<int>(s.size()), s.c_str(),
374              readableTime(secPerIter, 2).c_str(),
375              metricReadable(itersPerSec, 2).c_str());
376     } else {
377       // Print with baseline
378       auto rel = baselineNsPerIter / nsPerIter * 100.0;
379       printf("%*s %7.2f%%  %9s  %7s\n",
380              static_cast<int>(s.size()), s.c_str(),
381              rel,
382              readableTime(secPerIter, 2).c_str(),
383              metricReadable(itersPerSec, 2).c_str());
384     }
385   }
386   separator('=');
387 }
388
389 static void printBenchmarkResultsAsJson(
390   const vector<tuple<const char*, const char*, double> >& data) {
391   dynamic d = dynamic::object;
392   for (auto& datum: data) {
393     d[std::get<1>(datum)] = std::get<2>(datum) * 1000.;
394   }
395
396   printf("%s\n", toPrettyJson(d).c_str());
397 }
398
399 static void printBenchmarkResults(
400   const vector<tuple<const char*, const char*, double> >& data) {
401
402   if (FLAGS_json) {
403     printBenchmarkResultsAsJson(data);
404   } else {
405     printBenchmarkResultsAsTable(data);
406   }
407 }
408
409 void runBenchmarks() {
410   CHECK(!benchmarks.empty());
411
412   vector<tuple<const char*, const char*, double>> results;
413   results.reserve(benchmarks.size() - 1);
414
415   std::unique_ptr<boost::regex> bmRegex;
416   if (!FLAGS_bm_regex.empty()) {
417     bmRegex.reset(new boost::regex(FLAGS_bm_regex));
418   }
419
420   // PLEASE KEEP QUIET. MEASUREMENTS IN PROGRESS.
421
422   auto const globalBaseline = runBenchmarkGetNSPerIteration(
423     get<2>(benchmarks.front()), 0);
424   FOR_EACH_RANGE (i, 1, benchmarks.size()) {
425     double elapsed = 0.0;
426     if (!strcmp(get<1>(benchmarks[i]), "-") == 0) { // skip separators
427       if (bmRegex && !boost::regex_search(get<1>(benchmarks[i]), *bmRegex)) {
428         continue;
429       }
430       elapsed = runBenchmarkGetNSPerIteration(get<2>(benchmarks[i]),
431                                               globalBaseline);
432     }
433     results.emplace_back(get<0>(benchmarks[i]),
434                          get<1>(benchmarks[i]), elapsed);
435   }
436
437   // PLEASE MAKE NOISE. MEASUREMENTS DONE.
438
439   printBenchmarkResults(results);
440 }
441
442 } // namespace folly