NULL -> nullptr
[folly.git] / folly / Benchmark.cpp
1 /*
2  * Copyright 2014 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,
214         min<uint64_t>(resolutionInNs * 100000, 1000000000ULL));
215
216   // We do measurements in several epochs and take the minimum, to
217   // account for jitter.
218   static const unsigned int epochs = 1000;
219   // We establish a total time budget as we don't want a measurement
220   // to take too long. This will curtail the number of actual epochs.
221   const uint64_t timeBudgetInNs = FLAGS_bm_max_secs * 1000000000;
222   timespec global;
223   CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &global));
224
225   double epochResults[epochs] = { 0 };
226   size_t actualEpochs = 0;
227
228   for (; actualEpochs < epochs; ++actualEpochs) {
229     for (unsigned int n = FLAGS_bm_min_iters; n < (1UL << 30); n *= 2) {
230       auto const nsecs = fun(n);
231       if (nsecs < minNanoseconds) {
232         continue;
233       }
234       // We got an accurate enough timing, done. But only save if
235       // smaller than the current result.
236       epochResults[actualEpochs] = max(0.0, double(nsecs) / n - globalBaseline);
237       // Done with the current epoch, we got a meaningful timing.
238       break;
239     }
240     timespec now;
241     CHECK_EQ(0, clock_gettime(CLOCK_REALTIME, &now));
242     if (detail::timespecDiff(now, global) >= timeBudgetInNs) {
243       // No more time budget available.
244       ++actualEpochs;
245       break;
246     }
247   }
248
249   // If the benchmark was basically drowned in baseline noise, it's
250   // possible it became negative.
251   return max(0.0, estimateTime(epochResults, epochResults + actualEpochs));
252 }
253
254 struct ScaleInfo {
255   double boundary;
256   const char* suffix;
257 };
258
259 static const ScaleInfo kTimeSuffixes[] {
260   { 365.25 * 24 * 3600, "years" },
261   { 24 * 3600, "days" },
262   { 3600, "hr" },
263   { 60, "min" },
264   { 1, "s" },
265   { 1E-3, "ms" },
266   { 1E-6, "us" },
267   { 1E-9, "ns" },
268   { 1E-12, "ps" },
269   { 1E-15, "fs" },
270   { 0, nullptr },
271 };
272
273 static const ScaleInfo kMetricSuffixes[] {
274   { 1E24, "Y" },  // yotta
275   { 1E21, "Z" },  // zetta
276   { 1E18, "X" },  // "exa" written with suffix 'X' so as to not create
277                   //   confusion with scientific notation
278   { 1E15, "P" },  // peta
279   { 1E12, "T" },  // terra
280   { 1E9, "G" },   // giga
281   { 1E6, "M" },   // mega
282   { 1E3, "K" },   // kilo
283   { 1, "" },
284   { 1E-3, "m" },  // milli
285   { 1E-6, "u" },  // micro
286   { 1E-9, "n" },  // nano
287   { 1E-12, "p" }, // pico
288   { 1E-15, "f" }, // femto
289   { 1E-18, "a" }, // atto
290   { 1E-21, "z" }, // zepto
291   { 1E-24, "y" }, // yocto
292   { 0, nullptr },
293 };
294
295 static string humanReadable(double n, unsigned int decimals,
296                             const ScaleInfo* scales) {
297   if (std::isinf(n) || std::isnan(n)) {
298     return folly::to<string>(n);
299   }
300
301   const double absValue = fabs(n);
302   const ScaleInfo* scale = scales;
303   while (absValue < scale[0].boundary && scale[1].suffix != nullptr) {
304     ++scale;
305   }
306
307   const double scaledValue = n / scale->boundary;
308   return stringPrintf("%.*f%s", decimals, scaledValue, scale->suffix);
309 }
310
311 static string readableTime(double n, unsigned int decimals) {
312   return humanReadable(n, decimals, kTimeSuffixes);
313 }
314
315 static string metricReadable(double n, unsigned int decimals) {
316   return humanReadable(n, decimals, kMetricSuffixes);
317 }
318
319 static void printBenchmarkResultsAsTable(
320   const vector<tuple<const char*, const char*, double> >& data) {
321   // Width available
322   static const uint columns = 76;
323
324   // Compute the longest benchmark name
325   size_t longestName = 0;
326   FOR_EACH_RANGE (i, 1, benchmarks.size()) {
327     longestName = max(longestName, strlen(get<1>(benchmarks[i])));
328   }
329
330   // Print a horizontal rule
331   auto separator = [&](char pad) {
332     puts(string(columns, pad).c_str());
333   };
334
335   // Print header for a file
336   auto header = [&](const char* file) {
337     separator('=');
338     printf("%-*srelative  time/iter  iters/s\n",
339            columns - 28, file);
340     separator('=');
341   };
342
343   double baselineNsPerIter = numeric_limits<double>::max();
344   const char* lastFile = "";
345
346   for (auto& datum : data) {
347     auto file = get<0>(datum);
348     if (strcmp(file, lastFile)) {
349       // New file starting
350       header(file);
351       lastFile = file;
352     }
353
354     string s = get<1>(datum);
355     if (s == "-") {
356       separator('-');
357       continue;
358     }
359     bool useBaseline /* = void */;
360     if (s[0] == '%') {
361       s.erase(0, 1);
362       useBaseline = true;
363     } else {
364       baselineNsPerIter = get<2>(datum);
365       useBaseline = false;
366     }
367     s.resize(columns - 29, ' ');
368     auto nsPerIter = get<2>(datum);
369     auto secPerIter = nsPerIter / 1E9;
370     auto itersPerSec = 1 / secPerIter;
371     if (!useBaseline) {
372       // Print without baseline
373       printf("%*s           %9s  %7s\n",
374              static_cast<int>(s.size()), s.c_str(),
375              readableTime(secPerIter, 2).c_str(),
376              metricReadable(itersPerSec, 2).c_str());
377     } else {
378       // Print with baseline
379       auto rel = baselineNsPerIter / nsPerIter * 100.0;
380       printf("%*s %7.2f%%  %9s  %7s\n",
381              static_cast<int>(s.size()), s.c_str(),
382              rel,
383              readableTime(secPerIter, 2).c_str(),
384              metricReadable(itersPerSec, 2).c_str());
385     }
386   }
387   separator('=');
388 }
389
390 static void printBenchmarkResultsAsJson(
391   const vector<tuple<const char*, const char*, double> >& data) {
392   dynamic d = dynamic::object;
393   for (auto& datum: data) {
394     d[std::get<1>(datum)] = std::get<2>(datum) * 1000.;
395   }
396
397   printf("%s\n", toPrettyJson(d).c_str());
398 }
399
400 static void printBenchmarkResults(
401   const vector<tuple<const char*, const char*, double> >& data) {
402
403   if (FLAGS_json) {
404     printBenchmarkResultsAsJson(data);
405   } else {
406     printBenchmarkResultsAsTable(data);
407   }
408 }
409
410 void runBenchmarks() {
411   CHECK(!benchmarks.empty());
412
413   vector<tuple<const char*, const char*, double>> results;
414   results.reserve(benchmarks.size() - 1);
415
416   std::unique_ptr<boost::regex> bmRegex;
417   if (!FLAGS_bm_regex.empty()) {
418     bmRegex.reset(new boost::regex(FLAGS_bm_regex));
419   }
420
421   // PLEASE KEEP QUIET. MEASUREMENTS IN PROGRESS.
422
423   auto const globalBaseline = runBenchmarkGetNSPerIteration(
424     get<2>(benchmarks.front()), 0);
425   FOR_EACH_RANGE (i, 1, benchmarks.size()) {
426     double elapsed = 0.0;
427     if (strcmp(get<1>(benchmarks[i]), "-") != 0) { // skip separators
428       if (bmRegex && !boost::regex_search(get<1>(benchmarks[i]), *bmRegex)) {
429         continue;
430       }
431       elapsed = runBenchmarkGetNSPerIteration(get<2>(benchmarks[i]),
432                                               globalBaseline);
433     }
434     results.emplace_back(get<0>(benchmarks[i]),
435                          get<1>(benchmarks[i]), elapsed);
436   }
437
438   // PLEASE MAKE NOISE. MEASUREMENTS DONE.
439
440   printBenchmarkResults(results);
441 }
442
443 } // namespace folly