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