2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 // @author Andrei Alexandrescu (andrei.alexandrescu@fb.com)
19 #include <folly/Benchmark.h>
29 #include <boost/regex.hpp>
31 #include <folly/Foreach.h>
32 #include <folly/String.h>
33 #include <folly/json.h>
37 DEFINE_bool(benchmark, false, "Run benchmarks.");
38 DEFINE_bool(json, false, "Output in JSON format.");
43 "Only benchmarks whose names match this regex will be run.");
48 "Minimum # of microseconds we'll accept for each benchmark.");
53 "Minimum # of iterations we'll try for each benchmark.");
58 "Maximum # of iterations we'll try for each benchmark.");
63 "Maximum # of seconds we'll spend on each benchmark.");
67 std::chrono::high_resolution_clock::duration BenchmarkSuspender::timeSpent;
69 typedef function<detail::TimeIterPair(unsigned int)> BenchmarkFun;
72 vector<tuple<string, string, BenchmarkFun>>& benchmarks() {
73 static vector<tuple<string, string, BenchmarkFun>> _benchmarks;
77 #define FB_FOLLY_GLOBAL_BENCHMARK_BASELINE fbFollyGlobalBenchmarkBaseline
78 #define FB_STRINGIZE_X2(x) FB_STRINGIZE(x)
80 // Add the global baseline
81 BENCHMARK(FB_FOLLY_GLOBAL_BENCHMARK_BASELINE) {
89 size_t getGlobalBenchmarkBaselineIndex() {
90 const char *global = FB_STRINGIZE_X2(FB_FOLLY_GLOBAL_BENCHMARK_BASELINE);
91 auto it = std::find_if(
94 [global](const tuple<string, string, BenchmarkFun> &v) {
95 return get<1>(v) == global;
98 CHECK(it != benchmarks().end());
99 return size_t(std::distance(benchmarks().begin(), it));
102 #undef FB_STRINGIZE_X2
103 #undef FB_FOLLY_GLOBAL_BENCHMARK_BASELINE
105 void detail::addBenchmarkImpl(const char* file, const char* name,
107 benchmarks().emplace_back(file, name, std::move(fun));
111 * Given a bunch of benchmark samples, estimate the actual run time.
113 static double estimateTime(double * begin, double * end) {
116 // Current state of the art: get the minimum. After some
117 // experimentation, it seems taking the minimum is the best.
118 return *min_element(begin, end);
121 static double runBenchmarkGetNSPerIteration(const BenchmarkFun& fun,
122 const double globalBaseline) {
123 using std::chrono::duration_cast;
124 using std::chrono::high_resolution_clock;
125 using std::chrono::microseconds;
126 using std::chrono::nanoseconds;
127 using std::chrono::seconds;
129 // They key here is accuracy; too low numbers means the accuracy was
130 // coarse. We up the ante until we get to at least minNanoseconds
133 std::is_same<high_resolution_clock::duration, nanoseconds>::value,
134 "High resolution clock must be nanosecond resolution.");
135 // We choose a minimum minimum (sic) of 100,000 nanoseconds, but if
136 // the clock resolution is worse than that, it will be larger. In
137 // essence we're aiming at making the quantization noise 0.01%.
138 static const auto minNanoseconds = std::max<nanoseconds>(
139 nanoseconds(100000), microseconds(FLAGS_bm_min_usec));
141 // We do measurements in several epochs and take the minimum, to
142 // account for jitter.
143 static const unsigned int epochs = 1000;
144 // We establish a total time budget as we don't want a measurement
145 // to take too long. This will curtail the number of actual epochs.
146 const auto timeBudget = seconds(FLAGS_bm_max_secs);
147 auto global = high_resolution_clock::now();
149 double epochResults[epochs] = { 0 };
150 size_t actualEpochs = 0;
152 for (; actualEpochs < epochs; ++actualEpochs) {
153 const auto maxIters = uint32_t(FLAGS_bm_max_iters);
154 for (auto n = uint32_t(FLAGS_bm_min_iters); n < maxIters; n *= 2) {
155 auto const nsecsAndIter = fun(static_cast<unsigned int>(n));
156 if (nsecsAndIter.first < minNanoseconds) {
159 // We got an accurate enough timing, done. But only save if
160 // smaller than the current result.
161 auto nsecs = duration_cast<nanoseconds>(nsecsAndIter.first).count();
162 epochResults[actualEpochs] =
163 max(0.0, double(nsecs) / nsecsAndIter.second - globalBaseline);
164 // Done with the current epoch, we got a meaningful timing.
167 auto now = high_resolution_clock::now();
168 if (now - global >= timeBudget) {
169 // No more time budget available.
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));
185 static const ScaleInfo kTimeSuffixes[] {
186 { 365.25 * 24 * 3600, "years" },
187 { 24 * 3600, "days" },
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
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
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);
227 const double absValue = fabs(n);
228 const ScaleInfo* scale = scales;
229 while (absValue < scale[0].boundary && scale[1].suffix != nullptr) {
233 const double scaledValue = n / scale->boundary;
234 return stringPrintf("%.*f%s", decimals, scaledValue, scale->suffix);
237 static string readableTime(double n, unsigned int decimals) {
238 return humanReadable(n, decimals, kTimeSuffixes);
241 static string metricReadable(double n, unsigned int decimals) {
242 return humanReadable(n, decimals, kMetricSuffixes);
245 static void printBenchmarkResultsAsTable(
246 const vector<tuple<string, string, double> >& data) {
248 static const unsigned int columns = 76;
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());
256 // Print a horizontal rule
257 auto separator = [&](char pad) {
258 puts(string(columns, pad).c_str());
261 // Print header for a file
262 auto header = [&](const string& file) {
264 printf("%-*srelative time/iter iters/s\n",
265 columns - 28, file.c_str());
269 double baselineNsPerIter = numeric_limits<double>::max();
272 for (auto& datum : data) {
273 auto file = get<0>(datum);
274 if (file != lastFile) {
280 string s = get<1>(datum);
285 bool useBaseline /* = void */;
290 baselineNsPerIter = get<2>(datum);
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()
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());
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(),
311 readableTime(secPerIter, 2).c_str(),
312 metricReadable(itersPerSec, 2).c_str());
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.;
325 printf("%s\n", toPrettyJson(d).c_str());
328 static void printBenchmarkResults(
329 const vector<tuple<string, string, double> >& data) {
332 printBenchmarkResultsAsJson(data);
334 printBenchmarkResultsAsTable(data);
338 void runBenchmarks() {
339 CHECK(!benchmarks().empty());
341 vector<tuple<string, string, double>> results;
342 results.reserve(benchmarks().size() - 1);
344 std::unique_ptr<boost::regex> bmRegex;
345 if (!FLAGS_bm_regex.empty()) {
346 bmRegex.reset(new boost::regex(FLAGS_bm_regex));
349 // PLEASE KEEP QUIET. MEASUREMENTS IN PROGRESS.
351 size_t baselineIndex = getGlobalBenchmarkBaselineIndex();
353 auto const globalBaseline =
354 runBenchmarkGetNSPerIteration(get<2>(benchmarks()[baselineIndex]), 0);
355 FOR_EACH_RANGE (i, 0, benchmarks().size()) {
356 if (i == baselineIndex) {
359 double elapsed = 0.0;
360 if (get<1>(benchmarks()[i]) != "-") { // skip separators
361 if (bmRegex && !boost::regex_search(get<1>(benchmarks()[i]), *bmRegex)) {
364 elapsed = runBenchmarkGetNSPerIteration(get<2>(benchmarks()[i]),
367 results.emplace_back(get<0>(benchmarks()[i]),
368 get<1>(benchmarks()[i]), elapsed);
371 // PLEASE MAKE NOISE. MEASUREMENTS DONE.
373 printBenchmarkResults(results);