Debian Codegraph @

benchmarks/nanobench.h

raw
1 // __ _ _______ __ _ _____ ______ _______ __ _ _______ _ _
2 // | \ | |_____| | \ | | | |_____] |______ | \ | | |_____|
3 // | \_| | | | \_| |_____| |_____] |______ | \_| |_____ | |
4 //
5 // Microbenchmark framework for C++11/14/17/20
6 // https://github.com/martinus/nanobench
7 //
8 // Licensed under the MIT License <http://opensource.org/licenses/MIT>.
9 // SPDX-License-Identifier: MIT
10 // Copyright (c) 2019-2021 Martin Ankerl <[email protected]>
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining a copy
13 // of this software and associated documentation files (the "Software"), to deal
14 // in the Software without restriction, including without limitation the rights
15 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 // copies of the Software, and to permit persons to whom the Software is
17 // furnished to do so, subject to the following conditions:
18 //
19 // The above copyright notice and this permission notice shall be included in all
20 // copies or substantial portions of the Software.
21 //
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 // SOFTWARE.
29
30 #ifndef ANKERL_NANOBENCH_H_INCLUDED
31 #define ANKERL_NANOBENCH_H_INCLUDED
32
33 // see https://semver.org/
34 #define ANKERL_NANOBENCH_VERSION_MAJOR 4 // incompatible API changes
35 #define ANKERL_NANOBENCH_VERSION_MINOR 3 // backwards-compatible changes
36 #define ANKERL_NANOBENCH_VERSION_PATCH 4 // backwards-compatible bug fixes
37
38 ///////////////////////////////////////////////////////////////////////////////////////////////////
39 // public facing api - as minimal as possible
40 ///////////////////////////////////////////////////////////////////////////////////////////////////
41
42 #include <chrono> // high_resolution_clock
43 #include <cstring> // memcpy
44 #include <iosfwd> // for std::ostream* custom output target in Config
45 #include <string> // all names
46 #include <vector> // holds all results
47
48 #define ANKERL_NANOBENCH(x) ANKERL_NANOBENCH_PRIVATE_##x()
49
50 #define ANKERL_NANOBENCH_PRIVATE_CXX() __cplusplus
51 #define ANKERL_NANOBENCH_PRIVATE_CXX98() 199711L
52 #define ANKERL_NANOBENCH_PRIVATE_CXX11() 201103L
53 #define ANKERL_NANOBENCH_PRIVATE_CXX14() 201402L
54 #define ANKERL_NANOBENCH_PRIVATE_CXX17() 201703L
55
56 #if ANKERL_NANOBENCH(CXX) >= ANKERL_NANOBENCH(CXX17)
57 # define ANKERL_NANOBENCH_PRIVATE_NODISCARD() [[nodiscard]]
58 #else
59 # define ANKERL_NANOBENCH_PRIVATE_NODISCARD()
60 #endif
61
62 #if defined(__clang__)
63 # define ANKERL_NANOBENCH_PRIVATE_IGNORE_PADDED_PUSH() \
64 _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wpadded\"")
65 # define ANKERL_NANOBENCH_PRIVATE_IGNORE_PADDED_POP() _Pragma("clang diagnostic pop")
66 #else
67 # define ANKERL_NANOBENCH_PRIVATE_IGNORE_PADDED_PUSH()
68 # define ANKERL_NANOBENCH_PRIVATE_IGNORE_PADDED_POP()
69 #endif
70
71 #if defined(__GNUC__)
72 # define ANKERL_NANOBENCH_PRIVATE_IGNORE_EFFCPP_PUSH() _Pragma("GCC diagnostic push") _Pragma("GCC diagnostic ignored \"-Weffc++\"")
73 # define ANKERL_NANOBENCH_PRIVATE_IGNORE_EFFCPP_POP() _Pragma("GCC diagnostic pop")
74 #else
75 # define ANKERL_NANOBENCH_PRIVATE_IGNORE_EFFCPP_PUSH()
76 # define ANKERL_NANOBENCH_PRIVATE_IGNORE_EFFCPP_POP()
77 #endif
78
79 #if defined(ANKERL_NANOBENCH_LOG_ENABLED)
80 # include <iostream>
81 # define ANKERL_NANOBENCH_LOG(x) \
82 do { \
83 std::cout << __FUNCTION__ << "@" << __LINE__ << ": " << x << std::endl; \
84 } while (0)
85 #else
86 # define ANKERL_NANOBENCH_LOG(x) \
87 do { \
88 } while (0)
89 #endif
90
91 #if defined(__linux__) && defined(PERF_EVENT_IOC_ID) && defined(PERF_COUNT_HW_REF_CPU_CYCLES) && defined(PERF_FLAG_FD_CLOEXEC) && \
92 !defined(ANKERL_NANOBENCH_DISABLE_PERF_COUNTERS)
93 // only enable perf counters on kernel 3.14 which seems to have all the necessary defines. The three PERF_... defines are not in
94 // kernel 2.6.32 (all others are).
95 # define ANKERL_NANOBENCH_PRIVATE_PERF_COUNTERS() 1
96 #else
97 # define ANKERL_NANOBENCH_PRIVATE_PERF_COUNTERS() 0
98 #endif
99
100 #if defined(__clang__)
101 # define ANKERL_NANOBENCH_NO_SANITIZE(...) __attribute__((no_sanitize(__VA_ARGS__)))
102 #else
103 # define ANKERL_NANOBENCH_NO_SANITIZE(...)
104 #endif
105
106 #if defined(_MSC_VER)
107 # define ANKERL_NANOBENCH_PRIVATE_NOINLINE() __declspec(noinline)
108 #else
109 # define ANKERL_NANOBENCH_PRIVATE_NOINLINE() __attribute__((noinline))
110 #endif
111
112 // workaround missing "is_trivially_copyable" in g++ < 5.0
113 // See https://stackoverflow.com/a/31798726/48181
114 #if defined(__GNUC__) && __GNUC__ < 5
115 # define ANKERL_NANOBENCH_IS_TRIVIALLY_COPYABLE(...) __has_trivial_copy(__VA_ARGS__)
116 #else
117 # define ANKERL_NANOBENCH_IS_TRIVIALLY_COPYABLE(...) std::is_trivially_copyable<__VA_ARGS__>::value
118 #endif
119
120 // declarations ///////////////////////////////////////////////////////////////////////////////////
121
122 namespace ankerl {
123 namespace nanobench {
124
125 using Clock = std::conditional<std::chrono::high_resolution_clock::is_steady, std::chrono::high_resolution_clock,
126 std::chrono::steady_clock>::type;
127 class Bench;
128 struct Config;
129 class Result;
130 class Rng;
131 class BigO;
132
133 /**
134 * @brief Renders output from a mustache-like template and benchmark results.
135 *
136 * The templating facility here is heavily inspired by [mustache - logic-less templates](https://mustache.github.io/).
137 * It adds a few more features that are necessary to get all of the captured data out of nanobench. Please read the
138 * excellent [mustache manual](https://mustache.github.io/mustache.5.html) to see what this is all about.
139 *
140 * nanobench output has two nested layers, *result* and *measurement*. Here is a hierarchy of the allowed tags:
141 *
142 * * `{{#result}}` Marks the begin of the result layer. Whatever comes after this will be instantiated as often as
143 * a benchmark result is available. Within it, you can use these tags:
144 *
145 * * `{{title}}` See Bench::title().
146 *
147 * * `{{name}}` Benchmark name, usually directly provided with Bench::run(), but can also be set with Bench::name().
148 *
149 * * `{{unit}}` Unit, e.g. `byte`. Defaults to `op`, see Bench::title().
150 *
151 * * `{{batch}}` Batch size, see Bench::batch().
152 *
153 * * `{{complexityN}}` Value used for asymptotic complexity calculation. See Bench::complexityN().
154 *
155 * * `{{epochs}}` Number of epochs, see Bench::epochs().
156 *
157 * * `{{clockResolution}}` Accuracy of the clock, i.e. what's the smallest time possible to measure with the clock.
158 * For modern systems, this can be around 20 ns. This value is automatically determined by nanobench at the first
159 * benchmark that is run, and used as a static variable throughout the application's runtime.
160 *
161 * * `{{clockResolutionMultiple}}` Configuration multiplier for `clockResolution`. See Bench::clockResolutionMultiple().
162 * This is the target runtime for each measurement (epoch). That means the more accurate your clock is, the faster
163 * will be the benchmark. Basing the measurement's runtime on the clock resolution is the main reason why nanobench is so fast.
164 *
165 * * `{{maxEpochTime}}` Configuration for a maximum time each measurement (epoch) is allowed to take. Note that at least
166 * a single iteration will be performed, even when that takes longer than maxEpochTime. See Bench::maxEpochTime().
167 *
168 * * `{{minEpochTime}}` Minimum epoch time, usually not set. See Bench::minEpochTime().
169 *
170 * * `{{minEpochIterations}}` See Bench::minEpochIterations().
171 *
172 * * `{{epochIterations}}` See Bench::epochIterations().
173 *
174 * * `{{warmup}}` Number of iterations used before measuring starts. See Bench::warmup().
175 *
176 * * `{{relative}}` True or false, depending on the setting you have used. See Bench::relative().
177 *
178 * Apart from these tags, it is also possible to use some mathematical operations on the measurement data. The operations
179 * are of the form `{{command(name)}}`. Currently `name` can be one of `elapsed`, `iterations`. If performance counters
180 * are available (currently only on current Linux systems), you also have `pagefaults`, `cpucycles`,
181 * `contextswitches`, `instructions`, `branchinstructions`, and `branchmisses`. All the measuers (except `iterations`) are
182 * provided for a single iteration (so `elapsed` is the time a single iteration took). The following tags are available:
183 *
184 * * `{{median(<name>)}}` Calculate median of a measurement data set, e.g. `{{median(elapsed)}}`.
185 *
186 * * `{{average(<name>)}}` Average (mean) calculation.
187 *
188 * * `{{medianAbsolutePercentError(<name>)}}` Calculates MdAPE, the Median Absolute Percentage Error. The MdAPE is an excellent
189 * metric for the variation of measurements. It is more robust to outliers than the
190 * [Mean absolute percentage error (M-APE)](https://en.wikipedia.org/wiki/Mean_absolute_percentage_error).
191 * @f[
192 * \mathrm{MdAPE}(e) = \mathrm{med}\{| \frac{e_i - \mathrm{med}\{e\}}{e_i}| \}
193 * @f]
194 * E.g. for *elapsed*: First, @f$ \mathrm{med}\{e\} @f$ calculates the median by sorting and then taking the middle element
195 * of all *elapsed* measurements. This is used to calculate the absolute percentage
196 * error to this median for each measurement, as in @f$ | \frac{e_i - \mathrm{med}\{e\}}{e_i}| @f$. All these results
197 * are sorted, and the middle value is chosen as the median absolute percent error.
198 *
199 * This measurement is a bit hard to interpret, but it is very robust against outliers. E.g. a value of 5% means that half of the
200 * measurements deviate less than 5% from the median, and the other deviate more than 5% from the median.
201 *
202 * * `{{sum(<name>)}}` Sums of all the measurements. E.g. `{{sum(iterations)}}` will give you the total number of iterations
203 * measured in this benchmark.
204 *
205 * * `{{minimum(<name>)}}` Minimum of all measurements.
206 *
207 * * `{{maximum(<name>)}}` Maximum of all measurements.
208 *
209 * * `{{sumProduct(<first>, <second>)}}` Calculates the sum of the products of corresponding measures:
210 * @f[
211 * \mathrm{sumProduct}(a,b) = \sum_{i=1}^{n}a_i\cdot b_i
212 * @f]
213 * E.g. to calculate total runtime of the benchmark, you multiply iterations with elapsed time for each measurement, and
214 * sum these results up:
215 * `{{sumProduct(iterations, elapsed)}}`.
216 *
217 * * `{{#measurement}}` To access individual measurement results, open the begin tag for measurements.
218 *
219 * * `{{elapsed}}` Average elapsed wall clock time per iteration, in seconds.
220 *
221 * * `{{iterations}}` Number of iterations in the measurement. The number of iterations will fluctuate due
222 * to some applied randomness, to enhance accuracy.
223 *
224 * * `{{pagefaults}}` Average number of pagefaults per iteration.
225 *
226 * * `{{cpucycles}}` Average number of CPU cycles processed per iteration.
227 *
228 * * `{{contextswitches}}` Average number of context switches per iteration.
229 *
230 * * `{{instructions}}` Average number of retired instructions per iteration.
231 *
232 * * `{{branchinstructions}}` Average number of branches executed per iteration.
233 *
234 * * `{{branchmisses}}` Average number of branches that were missed per iteration.
235 *
236 * * `{{/measurement}}` Ends the measurement tag.
237 *
238 * * `{{/result}}` Marks the end of the result layer. This is the end marker for the template part that will be instantiated
239 * for each benchmark result.
240 *
241 *
242 * For the layer tags *result* and *measurement* you additionally can use these special markers:
243 *
244 * * ``{{#-first}}`` - Begin marker of a template that will be instantiated *only for the first* entry in the layer. Use is only
245 * allowed between the begin and end marker of the layer allowed. So between ``{{#result}}`` and ``{{/result}}``, or between
246 * ``{{#measurement}}`` and ``{{/measurement}}``. Finish the template with ``{{/-first}}``.
247 *
248 * * ``{{^-first}}`` - Begin marker of a template that will be instantiated *for each except the first* entry in the layer. This,
249 * this is basically the inversion of ``{{#-first}}``. Use is only allowed between the begin and end marker of the layer allowed.
250 * So between ``{{#result}}`` and ``{{/result}}``, or between ``{{#measurement}}`` and ``{{/measurement}}``.
251 *
252 * * ``{{/-first}}`` - End marker for either ``{{#-first}}`` or ``{{^-first}}``.
253 *
254 * * ``{{#-last}}`` - Begin marker of a template that will be instantiated *only for the last* entry in the layer. Use is only
255 * allowed between the begin and end marker of the layer allowed. So between ``{{#result}}`` and ``{{/result}}``, or between
256 * ``{{#measurement}}`` and ``{{/measurement}}``. Finish the template with ``{{/-last}}``.
257 *
258 * * ``{{^-last}}`` - Begin marker of a template that will be instantiated *for each except the last* entry in the layer. This,
259 * this is basically the inversion of ``{{#-last}}``. Use is only allowed between the begin and end marker of the layer allowed.
260 * So between ``{{#result}}`` and ``{{/result}}``, or between ``{{#measurement}}`` and ``{{/measurement}}``.
261 *
262 * * ``{{/-last}}`` - End marker for either ``{{#-last}}`` or ``{{^-last}}``.
263 *
264 @verbatim embed:rst
265
266 For an overview of all the possible data you can get out of nanobench, please see the tutorial at :ref:`tutorial-template-json`.
267
268 The templates that ship with nanobench are:
269
270 * :cpp:func:`templates::csv() <ankerl::nanobench::templates::csv()>`
271 * :cpp:func:`templates::json() <ankerl::nanobench::templates::json()>`
272 * :cpp:func:`templates::htmlBoxplot() <ankerl::nanobench::templates::htmlBoxplot()>`
273 * :cpp:func:`templates::pyperf() <ankerl::nanobench::templates::pyperf()>`
274
275 @endverbatim
276 *
277 * @param mustacheTemplate The template.
278 * @param bench Benchmark, containing all the results.
279 * @param out Output for the generated output.
280 */
281 void render(char const* mustacheTemplate, Bench const& bench, std::ostream& out);
282 void render(std::string const& mustacheTemplate, Bench const& bench, std::ostream& out);
283
284 /**
285 * Same as render(char const* mustacheTemplate, Bench const& bench, std::ostream& out), but for when
286 * you only have results available.
287 *
288 * @param mustacheTemplate The template.
289 * @param results All the results to be used for rendering.
290 * @param out Output for the generated output.
291 */
292 void render(char const* mustacheTemplate, std::vector<Result> const& results, std::ostream& out);
293 void render(std::string const& mustacheTemplate, std::vector<Result> const& results, std::ostream& out);
294
295 // Contains mustache-like templates
296 namespace templates {
297
298 /*!
299 @brief CSV data for the benchmark results.
300
301 Generates a comma-separated values dataset. First line is the header, each following line is a summary of each benchmark run.
302
303 @verbatim embed:rst
304 See the tutorial at :ref:`tutorial-template-csv` for an example.
305 @endverbatim
306 */
307 char const* csv() noexcept;
308
309 /*!
310 @brief HTML output that uses plotly to generate an interactive boxplot chart. See the tutorial for an example output.
311
312 The output uses only the elapsed wall clock time, and displays each epoch as a single dot.
313 @verbatim embed:rst
314 See the tutorial at :ref:`tutorial-template-html` for an example.
315 @endverbatim
316
317 @see ankerl::nanobench::render()
318 */
319 char const* htmlBoxplot() noexcept;
320
321 /*!
322 @brief Output in pyperf compatible JSON format, which can be used for more analyzations.
323 @verbatim embed:rst
324 See the tutorial at :ref:`tutorial-template-pyperf` for an example how to further analyze the output.
325 @endverbatim
326 */
327 char const* pyperf() noexcept;
328
329 /*!
330 @brief Template to generate JSON data.
331
332 The generated JSON data contains *all* data that has been generated. All times are as double values, in seconds. The output can get
333 quite large.
334 @verbatim embed:rst
335 See the tutorial at :ref:`tutorial-template-json` for an example.
336 @endverbatim
337 */
338 char const* json() noexcept;
339
340 } // namespace templates
341
342 namespace detail {
343
344 template <typename T>
345 struct PerfCountSet;
346
347 class IterationLogic;
348 class PerformanceCounters;
349
350 #if ANKERL_NANOBENCH(PERF_COUNTERS)
351 class LinuxPerformanceCounters;
352 #endif
353
354 } // namespace detail
355 } // namespace nanobench
356 } // namespace ankerl
357
358 // definitions ////////////////////////////////////////////////////////////////////////////////////
359
360 namespace ankerl {
361 namespace nanobench {
362 namespace detail {
363
364 template <typename T>
365 struct PerfCountSet {
366 T pageFaults{};
367 T cpuCycles{};
368 T contextSwitches{};
369 T instructions{};
370 T branchInstructions{};
371 T branchMisses{};
372 };
373
374 } // namespace detail
375
376 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
377 struct Config {
378 // actual benchmark config
379 std::string mBenchmarkTitle = "benchmark";
380 std::string mBenchmarkName = "noname";
381 std::string mUnit = "op";
382 double mBatch = 1.0;
383 double mComplexityN = -1.0;
384 size_t mNumEpochs = 11;
385 size_t mClockResolutionMultiple = static_cast<size_t>(1000);
386 std::chrono::nanoseconds mMaxEpochTime = std::chrono::milliseconds(100);
387 std::chrono::nanoseconds mMinEpochTime{};
388 uint64_t mMinEpochIterations{1};
389 uint64_t mEpochIterations{0}; // If not 0, run *exactly* these number of iterations per epoch.
390 uint64_t mWarmup = 0;
391 std::ostream* mOut = nullptr;
392 std::chrono::duration<double> mTimeUnit = std::chrono::nanoseconds{1};
393 std::string mTimeUnitName = "ns";
394 bool mShowPerformanceCounters = true;
395 bool mIsRelative = false;
396
397 Config();
398 ~Config();
399 Config& operator=(Config const&);
400 Config& operator=(Config&&);
401 Config(Config const&);
402 Config(Config&&) noexcept;
403 };
404 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
405
406 // Result returned after a benchmark has finished. Can be used as a baseline for relative().
407 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
408 class Result {
409 public:
410 enum class Measure : size_t {
411 elapsed,
412 iterations,
413 pagefaults,
414 cpucycles,
415 contextswitches,
416 instructions,
417 branchinstructions,
418 branchmisses,
419 _size
420 };
421
422 explicit Result(Config const& benchmarkConfig);
423
424 ~Result();
425 Result& operator=(Result const&);
426 Result& operator=(Result&&);
427 Result(Result const&);
428 Result(Result&&) noexcept;
429
430 // adds new measurement results
431 // all values are scaled by iters (except iters...)
432 void add(Clock::duration totalElapsed, uint64_t iters, detail::PerformanceCounters const& pc);
433
434 ANKERL_NANOBENCH(NODISCARD) Config const& config() const noexcept;
435
436 ANKERL_NANOBENCH(NODISCARD) double median(Measure m) const;
437 ANKERL_NANOBENCH(NODISCARD) double medianAbsolutePercentError(Measure m) const;
438 ANKERL_NANOBENCH(NODISCARD) double average(Measure m) const;
439 ANKERL_NANOBENCH(NODISCARD) double sum(Measure m) const noexcept;
440 ANKERL_NANOBENCH(NODISCARD) double sumProduct(Measure m1, Measure m2) const noexcept;
441 ANKERL_NANOBENCH(NODISCARD) double minimum(Measure m) const noexcept;
442 ANKERL_NANOBENCH(NODISCARD) double maximum(Measure m) const noexcept;
443
444 ANKERL_NANOBENCH(NODISCARD) bool has(Measure m) const noexcept;
445 ANKERL_NANOBENCH(NODISCARD) double get(size_t idx, Measure m) const;
446 ANKERL_NANOBENCH(NODISCARD) bool empty() const noexcept;
447 ANKERL_NANOBENCH(NODISCARD) size_t size() const noexcept;
448
449 // Finds string, if not found, returns _size.
450 static Measure fromString(std::string const& str);
451
452 private:
453 Config mConfig{};
454 std::vector<std::vector<double>> mNameToMeasurements{};
455 };
456 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
457
458 /**
459 * An extremely fast random generator. Currently, this implements *RomuDuoJr*, developed by Mark Overton. Source:
460 * http://www.romu-random.org/
461 *
462 * RomuDuoJr is extremely fast and provides reasonable good randomness. Not enough for large jobs, but definitely
463 * good enough for a benchmarking framework.
464 *
465 * * Estimated capacity: @f$ 2^{51} @f$ bytes
466 * * Register pressure: 4
467 * * State size: 128 bits
468 *
469 * This random generator is a drop-in replacement for the generators supplied by ``<random>``. It is not
470 * cryptographically secure. It's intended purpose is to be very fast so that benchmarks that make use
471 * of randomness are not distorted too much by the random generator.
472 *
473 * Rng also provides a few non-standard helpers, optimized for speed.
474 */
475 class Rng final {
476 public:
477 /**
478 * @brief This RNG provides 64bit randomness.
479 */
480 using result_type = uint64_t;
481
482 static constexpr uint64_t(min)();
483 static constexpr uint64_t(max)();
484
485 /**
486 * As a safety precausion, we don't allow copying. Copying a PRNG would mean you would have two random generators that produce the
487 * same sequence, which is generally not what one wants. Instead create a new rng with the default constructor Rng(), which is
488 * automatically seeded from `std::random_device`. If you really need a copy, use copy().
489 */
490 Rng(Rng const&) = delete;
491
492 /**
493 * Same as Rng(Rng const&), we don't allow assignment. If you need a new Rng create one with the default constructor Rng().
494 */
495 Rng& operator=(Rng const&) = delete;
496
497 // moving is ok
498 Rng(Rng&&) noexcept = default;
499 Rng& operator=(Rng&&) noexcept = default;
500 ~Rng() noexcept = default;
501
502 /**
503 * @brief Creates a new Random generator with random seed.
504 *
505 * Instead of a default seed (as the random generators from the STD), this properly seeds the random generator from
506 * `std::random_device`. It guarantees correct seeding. Note that seeding can be relatively slow, depending on the source of
507 * randomness used. So it is best to create a Rng once and use it for all your randomness purposes.
508 */
509 Rng();
510
511 /*!
512 Creates a new Rng that is seeded with a specific seed. Each Rng created from the same seed will produce the same randomness
513 sequence. This can be useful for deterministic behavior.
514
515 @verbatim embed:rst
516 .. note::
517
518 The random algorithm might change between nanobench releases. Whenever a faster and/or better random
519 generator becomes available, I will switch the implementation.
520 @endverbatim
521
522 As per the Romu paper, this seeds the Rng with splitMix64 algorithm and performs 10 initial rounds for further mixing up of the
523 internal state.
524
525 @param seed The 64bit seed. All values are allowed, even 0.
526 */
527 explicit Rng(uint64_t seed) noexcept;
528 Rng(uint64_t x, uint64_t y) noexcept;
529 Rng(std::vector<uint64_t> const& data);
530
531 /**
532 * Creates a copy of the Rng, thus the copy provides exactly the same random sequence as the original.
533 */
534 ANKERL_NANOBENCH(NODISCARD) Rng copy() const noexcept;
535
536 /**
537 * @brief Produces a 64bit random value. This should be very fast, thus it is marked as inline. In my benchmark, this is ~46 times
538 * faster than `std::default_random_engine` for producing 64bit random values. It seems that the fastest std contender is
539 * `std::mt19937_64`. Still, this RNG is 2-3 times as fast.
540 *
541 * @return uint64_t The next 64 bit random value.
542 */
543 inline uint64_t operator()() noexcept;
544
545 // This is slightly biased. See
546
547 /**
548 * Generates a random number between 0 and range (excluding range).
549 *
550 * The algorithm only produces 32bit numbers, and is slightly biased. The effect is quite small unless your range is close to the
551 * maximum value of an integer. It is possible to correct the bias with rejection sampling (see
552 * [here](https://lemire.me/blog/2016/06/30/fast-random-shuffling/), but this is most likely irrelevant in practices for the
553 * purposes of this Rng.
554 *
555 * See Daniel Lemire's blog post [A fast alternative to the modulo
556 * reduction](https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/)
557 *
558 * @param range Upper exclusive range. E.g a value of 3 will generate random numbers 0, 1, 2.
559 * @return uint32_t Generated random values in range [0, range(.
560 */
561 inline uint32_t bounded(uint32_t range) noexcept;
562
563 // random double in range [0, 1(
564 // see http://prng.di.unimi.it/
565
566 /**
567 * Provides a random uniform double value between 0 and 1. This uses the method described in [Generating uniform doubles in the
568 * unit interval](http://prng.di.unimi.it/), and is extremely fast.
569 *
570 * @return double Uniformly distributed double value in range [0,1(, excluding 1.
571 */
572 inline double uniform01() noexcept;
573
574 /**
575 * Shuffles all entries in the given container. Although this has a slight bias due to the implementation of bounded(), this is
576 * preferable to `std::shuffle` because it is over 5 times faster. See Daniel Lemire's blog post [Fast random
577 * shuffling](https://lemire.me/blog/2016/06/30/fast-random-shuffling/).
578 *
579 * @param container The whole container will be shuffled.
580 */
581 template <typename Container>
582 void shuffle(Container& container) noexcept;
583
584 /**
585 * Extracts the full state of the generator, e.g. for serialization. For this RNG this is just 2 values, but to stay API compatible
586 * with future implementations that potentially use more state, we use a vector.
587 *
588 * @return Vector containing the full state:
589 */
590 std::vector<uint64_t> state() const;
591
592 private:
593 static constexpr uint64_t rotl(uint64_t x, unsigned k) noexcept;
594
595 uint64_t mX;
596 uint64_t mY;
597 };
598
599 /**
600 * @brief Main entry point to nanobench's benchmarking facility.
601 *
602 * It holds configuration and results from one or more benchmark runs. Usually it is used in a single line, where the object is
603 * constructed, configured, and then a benchmark is run. E.g. like this:
604 *
605 * ankerl::nanobench::Bench().unit("byte").batch(1000).run("random fluctuations", [&] {
606 * // here be the benchmark code
607 * });
608 *
609 * In that example Bench() constructs the benchmark, it is then configured with unit() and batch(), and after configuration a
610 * benchmark is executed with run(). Once run() has finished, it prints the result to `std::cout`. It would also store the results
611 * in the Bench instance, but in this case the object is immediately destroyed so it's not available any more.
612 */
613 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
614 class Bench {
615 public:
616 /**
617 * @brief Creates a new benchmark for configuration and running of benchmarks.
618 */
619 Bench();
620
621 Bench(Bench&& other);
622 Bench& operator=(Bench&& other);
623 Bench(Bench const& other);
624 Bench& operator=(Bench const& other);
625 ~Bench() noexcept;
626
627 /*!
628 @brief Repeatedly calls `op()` based on the configuration, and performs measurements.
629
630 This call is marked with `noinline` to prevent the compiler to optimize beyond different benchmarks. This can have quite a big
631 effect on benchmark accuracy.
632
633 @verbatim embed:rst
634 .. note::
635
636 Each call to your lambda must have a side effect that the compiler can't possibly optimize it away. E.g. add a result to an
637 externally defined number (like `x` in the above example), and finally call `doNotOptimizeAway` on the variables the compiler
638 must not remove. You can also use :cpp:func:`ankerl::nanobench::doNotOptimizeAway` directly in the lambda, but be aware that
639 this has a small overhead.
640
641 @endverbatim
642
643 @tparam Op The code to benchmark.
644 */
645 template <typename Op>
646 ANKERL_NANOBENCH(NOINLINE)
647 Bench& run(char const* benchmarkName, Op&& op);
648
649 template <typename Op>
650 ANKERL_NANOBENCH(NOINLINE)
651 Bench& run(std::string const& benchmarkName, Op&& op);
652
653 /**
654 * @brief Same as run(char const* benchmarkName, Op op), but instead uses the previously set name.
655 * @tparam Op The code to benchmark.
656 */
657 template <typename Op>
658 ANKERL_NANOBENCH(NOINLINE)
659 Bench& run(Op&& op);
660
661 /**
662 * @brief Title of the benchmark, will be shown in the table header. Changing the title will start a new markdown table.
663 *
664 * @param benchmarkTitle The title of the benchmark.
665 */
666 Bench& title(char const* benchmarkTitle);
667 Bench& title(std::string const& benchmarkTitle);
668 ANKERL_NANOBENCH(NODISCARD) std::string const& title() const noexcept;
669
670 /// Name of the benchmark, will be shown in the table row.
671 Bench& name(char const* benchmarkName);
672 Bench& name(std::string const& benchmarkName);
673 ANKERL_NANOBENCH(NODISCARD) std::string const& name() const noexcept;
674
675 /**
676 * @brief Sets the batch size.
677 *
678 * E.g. number of processed byte, or some other metric for the size of the processed data in each iteration. If you benchmark
679 * hashing of a 1000 byte long string and want byte/sec as a result, you can specify 1000 as the batch size.
680 *
681 * @tparam T Any input type is internally cast to `double`.
682 * @param b batch size
683 */
684 template <typename T>
685 Bench& batch(T b) noexcept;
686 ANKERL_NANOBENCH(NODISCARD) double batch() const noexcept;
687
688 /**
689 * @brief Sets the operation unit.
690 *
691 * Defaults to "op". Could be e.g. "byte" for string processing. This is used for the table header, e.g. to show `ns/byte`. Use
692 * singular (*byte*, not *bytes*). A change clears the currently collected results.
693 *
694 * @param unit The unit name.
695 */
696 Bench& unit(char const* unit);
697 Bench& unit(std::string const& unit);
698 ANKERL_NANOBENCH(NODISCARD) std::string const& unit() const noexcept;
699
700 /**
701 * @brief Sets the time unit to be used for the default output.
702 *
703 * Nanobench defaults to using ns (nanoseconds) as output in the markdown. For some benchmarks this is too coarse, so it is
704 * possible to configure this. E.g. use `timeUnit(1ms, "ms")` to show `ms/op` instead of `ns/op`.
705 *
706 * @param tu Time unit to display the results in, default is 1ns.
707 * @param tuName Name for the time unit, default is "ns"
708 */
709 Bench& timeUnit(std::chrono::duration<double> const& tu, std::string const& tuName);
710 ANKERL_NANOBENCH(NODISCARD) std::string const& timeUnitName() const noexcept;
711 ANKERL_NANOBENCH(NODISCARD) std::chrono::duration<double> const& timeUnit() const noexcept;
712
713 /**
714 * @brief Set the output stream where the resulting markdown table will be printed to.
715 *
716 * The default is `&std::cout`. You can disable all output by setting `nullptr`.
717 *
718 * @param outstream Pointer to output stream, can be `nullptr`.
719 */
720 Bench& output(std::ostream* outstream) noexcept;
721 ANKERL_NANOBENCH(NODISCARD) std::ostream* output() const noexcept;
722
723 /**
724 * Modern processors have a very accurate clock, being able to measure as low as 20 nanoseconds. This is the main trick nanobech to
725 * be so fast: we find out how accurate the clock is, then run the benchmark only so often that the clock's accuracy is good enough
726 * for accurate measurements.
727 *
728 * The default is to run one epoch for 1000 times the clock resolution. So for 20ns resolution and 11 epochs, this gives a total
729 * runtime of
730 *
731 * @f[
732 * 20ns * 1000 * 11 \approx 0.2ms
733 * @f]
734 *
735 * To be precise, nanobench adds a 0-20% random noise to each evaluation. This is to prevent any aliasing effects, and further
736 * improves accuracy.
737 *
738 * Total runtime will be higher though: Some initial time is needed to find out the target number of iterations for each epoch, and
739 * there is some overhead involved to start & stop timers and calculate resulting statistics and writing the output.
740 *
741 * @param multiple Target number of times of clock resolution. Usually 1000 is a good compromise between runtime and accuracy.
742 */
743 Bench& clockResolutionMultiple(size_t multiple) noexcept;
744 ANKERL_NANOBENCH(NODISCARD) size_t clockResolutionMultiple() const noexcept;
745
746 /**
747 * @brief Controls number of epochs, the number of measurements to perform.
748 *
749 * The reported result will be the median of evaluation of each epoch. The higher you choose this, the more
750 * deterministic the result be and outliers will be more easily removed. Also the `err%` will be more accurate the higher this
751 * number is. Note that the `err%` will not necessarily decrease when number of epochs is increased. But it will be a more accurate
752 * representation of the benchmarked code's runtime stability.
753 *
754 * Choose the value wisely. In practice, 11 has been shown to be a reasonable choice between runtime performance and accuracy.
755 * This setting goes hand in hand with minEpocIterations() (or minEpochTime()). If you are more interested in *median* runtime, you
756 * might want to increase epochs(). If you are more interested in *mean* runtime, you might want to increase minEpochIterations()
757 * instead.
758 *
759 * @param numEpochs Number of epochs.
760 */
761 Bench& epochs(size_t numEpochs) noexcept;
762 ANKERL_NANOBENCH(NODISCARD) size_t epochs() const noexcept;
763
764 /**
765 * @brief Upper limit for the runtime of each epoch.
766 *
767 * As a safety precausion if the clock is not very accurate, we can set an upper limit for the maximum evaluation time per
768 * epoch. Default is 100ms. At least a single evaluation of the benchmark is performed.
769 *
770 * @see minEpochTime(), minEpochIterations()
771 *
772 * @param t Maximum target runtime for a single epoch.
773 */
774 Bench& maxEpochTime(std::chrono::nanoseconds t) noexcept;
775 ANKERL_NANOBENCH(NODISCARD) std::chrono::nanoseconds maxEpochTime() const noexcept;
776
777 /**
778 * @brief Minimum time each epoch should take.
779 *
780 * Default is zero, so we are fully relying on clockResolutionMultiple(). In most cases this is exactly what you want. If you see
781 * that the evaluation is unreliable with a high `err%`, you can increase either minEpochTime() or minEpochIterations().
782 *
783 * @see maxEpochTime(), minEpochIterations()
784 *
785 * @param t Minimum time each epoch should take.
786 */
787 Bench& minEpochTime(std::chrono::nanoseconds t) noexcept;
788 ANKERL_NANOBENCH(NODISCARD) std::chrono::nanoseconds minEpochTime() const noexcept;
789
790 /**
791 * @brief Sets the minimum number of iterations each epoch should take.
792 *
793 * Default is 1, and we rely on clockResolutionMultiple(). If the `err%` is high and you want a more smooth result, you might want
794 * to increase the minimum number or iterations, or increase the minEpochTime().
795 *
796 * @see minEpochTime(), maxEpochTime(), minEpochIterations()
797 *
798 * @param numIters Minimum number of iterations per epoch.
799 */
800 Bench& minEpochIterations(uint64_t numIters) noexcept;
801 ANKERL_NANOBENCH(NODISCARD) uint64_t minEpochIterations() const noexcept;
802
803 /**
804 * Sets exactly the number of iterations for each epoch. Ignores all other epoch limits. This forces nanobench to use exactly
805 * the given number of iterations for each epoch, not more and not less. Default is 0 (disabled).
806 *
807 * @param numIters Exact number of iterations to use. Set to 0 to disable.
808 */
809 Bench& epochIterations(uint64_t numIters) noexcept;
810 ANKERL_NANOBENCH(NODISCARD) uint64_t epochIterations() const noexcept;
811
812 /**
813 * @brief Sets a number of iterations that are initially performed without any measurements.
814 *
815 * Some benchmarks need a few evaluations to warm up caches / database / whatever access. Normally this should not be needed, since
816 * we show the median result so initial outliers will be filtered away automatically. If the warmup effect is large though, you
817 * might want to set it. Default is 0.
818 *
819 * @param numWarmupIters Number of warmup iterations.
820 */
821 Bench& warmup(uint64_t numWarmupIters) noexcept;
822 ANKERL_NANOBENCH(NODISCARD) uint64_t warmup() const noexcept;
823
824 /**
825 * @brief Marks the next run as the baseline.
826 *
827 * Call `relative(true)` to mark the run as the baseline. Successive runs will be compared to this run. It is calculated by
828 *
829 * @f[
830 * 100\% * \frac{baseline}{runtime}
831 * @f]
832 *
833 * * 100% means it is exactly as fast as the baseline
834 * * >100% means it is faster than the baseline. E.g. 200% means the current run is twice as fast as the baseline.
835 * * <100% means it is slower than the baseline. E.g. 50% means it is twice as slow as the baseline.
836 *
837 * See the tutorial section "Comparing Results" for example usage.
838 *
839 * @param isRelativeEnabled True to enable processing
840 */
841 Bench& relative(bool isRelativeEnabled) noexcept;
842 ANKERL_NANOBENCH(NODISCARD) bool relative() const noexcept;
843
844 /**
845 * @brief Enables/disables performance counters.
846 *
847 * On Linux nanobench has a powerful feature to use performance counters. This enables counting of retired instructions, count
848 * number of branches, missed branches, etc. On default this is enabled, but you can disable it if you don't need that feature.
849 *
850 * @param showPerformanceCounters True to enable, false to disable.
851 */
852 Bench& performanceCounters(bool showPerformanceCounters) noexcept;
853 ANKERL_NANOBENCH(NODISCARD) bool performanceCounters() const noexcept;
854
855 /**
856 * @brief Retrieves all benchmark results collected by the bench object so far.
857 *
858 * Each call to run() generates a Result that is stored within the Bench instance. This is mostly for advanced users who want to
859 * see all the nitty gritty detials.
860 *
861 * @return All results collected so far.
862 */
863 ANKERL_NANOBENCH(NODISCARD) std::vector<Result> const& results() const noexcept;
864
865 /*!
866 @verbatim embed:rst
867
868 Convenience shortcut to :cpp:func:`ankerl::nanobench::doNotOptimizeAway`.
869
870 @endverbatim
871 */
872 template <typename Arg>
873 Bench& doNotOptimizeAway(Arg&& arg);
874
875 /*!
876 @verbatim embed:rst
877
878 Sets N for asymptotic complexity calculation, so it becomes possible to calculate `Big O
879 <https://en.wikipedia.org/wiki/Big_O_notation>`_ from multiple benchmark evaluations.
880
881 Use :cpp:func:`ankerl::nanobench::Bench::complexityBigO` when the evaluation has finished. See the tutorial
882 :ref:`asymptotic-complexity` for details.
883
884 @endverbatim
885
886 @tparam T Any type is cast to `double`.
887 @param b Length of N for the next benchmark run, so it is possible to calculate `bigO`.
888 */
889 template <typename T>
890 Bench& complexityN(T b) noexcept;
891 ANKERL_NANOBENCH(NODISCARD) double complexityN() const noexcept;
892
893 /*!
894 Calculates [Big O](https://en.wikipedia.org/wiki/Big_O_notation>) of the results with all preconfigured complexity functions.
895 Currently these complexity functions are fitted into the benchmark results:
896
897 @f$ \mathcal{O}(1) @f$,
898 @f$ \mathcal{O}(n) @f$,
899 @f$ \mathcal{O}(\log{}n) @f$,
900 @f$ \mathcal{O}(n\log{}n) @f$,
901 @f$ \mathcal{O}(n^2) @f$,
902 @f$ \mathcal{O}(n^3) @f$.
903
904 If we e.g. evaluate the complexity of `std::sort`, this is the result of `std::cout << bench.complexityBigO()`:
905
906 ```
907 | coefficient | err% | complexity
908 |--------------:|-------:|------------
909 | 5.08935e-09 | 2.6% | O(n log n)
910 | 6.10608e-08 | 8.0% | O(n)
911 | 1.29307e-11 | 47.2% | O(n^2)
912 | 2.48677e-15 | 69.6% | O(n^3)
913 | 9.88133e-06 | 132.3% | O(log n)
914 | 5.98793e-05 | 162.5% | O(1)
915 ```
916
917 So in this case @f$ \mathcal{O}(n\log{}n) @f$ provides the best approximation.
918
919 @verbatim embed:rst
920 See the tutorial :ref:`asymptotic-complexity` for details.
921 @endverbatim
922 @return Evaluation results, which can be printed or otherwise inspected.
923 */
924 std::vector<BigO> complexityBigO() const;
925
926 /**
927 * @brief Calculates bigO for a custom function.
928 *
929 * E.g. to calculate the mean squared error for @f$ \mathcal{O}(\log{}\log{}n) @f$, which is not part of the default set of
930 * complexityBigO(), you can do this:
931 *
932 * ```
933 * auto logLogN = bench.complexityBigO("O(log log n)", [](double n) {
934 * return std::log2(std::log2(n));
935 * });
936 * ```
937 *
938 * The resulting mean squared error can be printed with `std::cout << logLogN`. E.g. it prints something like this:
939 *
940 * ```text
941 * 2.46985e-05 * O(log log n), rms=1.48121
942 * ```
943 *
944 * @tparam Op Type of mapping operation.
945 * @param name Name for the function, e.g. "O(log log n)"
946 * @param op Op's operator() maps a `double` with the desired complexity function, e.g. `log2(log2(n))`.
947 * @return BigO Error calculation, which is streamable to std::cout.
948 */
949 template <typename Op>
950 BigO complexityBigO(char const* name, Op op) const;
951
952 template <typename Op>
953 BigO complexityBigO(std::string const& name, Op op) const;
954
955 /*!
956 @verbatim embed:rst
957
958 Convenience shortcut to :cpp:func:`ankerl::nanobench::render`.
959
960 @endverbatim
961 */
962 Bench& render(char const* templateContent, std::ostream& os);
963 Bench& render(std::string const& templateContent, std::ostream& os);
964
965 Bench& config(Config const& benchmarkConfig);
966 ANKERL_NANOBENCH(NODISCARD) Config const& config() const noexcept;
967
968 private:
969 Config mConfig{};
970 std::vector<Result> mResults{};
971 };
972 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
973
974 /**
975 * @brief Makes sure none of the given arguments are optimized away by the compiler.
976 *
977 * @tparam Arg Type of the argument that shouldn't be optimized away.
978 * @param arg The input that we mark as being used, even though we don't do anything with it.
979 */
980 template <typename Arg>
981 void doNotOptimizeAway(Arg&& arg);
982
983 namespace detail {
984
985 #if defined(_MSC_VER)
986 void doNotOptimizeAwaySink(void const*);
987
988 template <typename T>
989 void doNotOptimizeAway(T const& val);
990
991 #else
992
993 // These assembly magic is directly from what Google Benchmark is doing. I have previously used what facebook's folly was doing, but
994 // this seemd to have compilation problems in some cases. Google Benchmark seemed to be the most well tested anyways.
995 // see https://github.com/google/benchmark/blob/master/include/benchmark/benchmark.h#L307
996 template <typename T>
997 void doNotOptimizeAway(T const& val) {
998 // NOLINTNEXTLINE(hicpp-no-assembler)
999 asm volatile("" : : "r,m"(val) : "memory");
1000 }
1001
1002 template <typename T>
1003 void doNotOptimizeAway(T& val) {
1004 # if defined(__clang__)
1005 // NOLINTNEXTLINE(hicpp-no-assembler)
1006 asm volatile("" : "+r,m"(val) : : "memory");
1007 # else
1008 // NOLINTNEXTLINE(hicpp-no-assembler)
1009 asm volatile("" : "+m,r"(val) : : "memory");
1010 # endif
1011 }
1012 #endif
1013
1014 // internally used, but visible because run() is templated.
1015 // Not movable/copy-able, so we simply use a pointer instead of unique_ptr. This saves us from
1016 // having to include <memory>, and the template instantiation overhead of unique_ptr which is unfortunately quite significant.
1017 ANKERL_NANOBENCH(IGNORE_EFFCPP_PUSH)
1018 class IterationLogic {
1019 public:
1020 explicit IterationLogic(Bench const& config) noexcept;
1021 ~IterationLogic();
1022
1023 ANKERL_NANOBENCH(NODISCARD) uint64_t numIters() const noexcept;
1024 void add(std::chrono::nanoseconds elapsed, PerformanceCounters const& pc) noexcept;
1025 void moveResultTo(std::vector<Result>& results) noexcept;
1026
1027 private:
1028 struct Impl;
1029 Impl* mPimpl;
1030 };
1031 ANKERL_NANOBENCH(IGNORE_EFFCPP_POP)
1032
1033 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
1034 class PerformanceCounters {
1035 public:
1036 PerformanceCounters(PerformanceCounters const&) = delete;
1037 PerformanceCounters& operator=(PerformanceCounters const&) = delete;
1038
1039 PerformanceCounters();
1040 ~PerformanceCounters();
1041
1042 void beginMeasure();
1043 void endMeasure();
1044 void updateResults(uint64_t numIters);
1045
1046 ANKERL_NANOBENCH(NODISCARD) PerfCountSet<uint64_t> const& val() const noexcept;
1047 ANKERL_NANOBENCH(NODISCARD) PerfCountSet<bool> const& has() const noexcept;
1048
1049 private:
1050 #if ANKERL_NANOBENCH(PERF_COUNTERS)
1051 LinuxPerformanceCounters* mPc = nullptr;
1052 #endif
1053 PerfCountSet<uint64_t> mVal{};
1054 PerfCountSet<bool> mHas{};
1055 };
1056 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
1057
1058 // Gets the singleton
1059 PerformanceCounters& performanceCounters();
1060
1061 } // namespace detail
1062
1063 class BigO {
1064 public:
1065 using RangeMeasure = std::vector<std::pair<double, double>>;
1066
1067 template <typename Op>
1068 static RangeMeasure mapRangeMeasure(RangeMeasure data, Op op) {
1069 for (auto& rangeMeasure : data) {
1070 rangeMeasure.first = op(rangeMeasure.first);
1071 }
1072 return data;
1073 }
1074
1075 static RangeMeasure collectRangeMeasure(std::vector<Result> const& results);
1076
1077 template <typename Op>
1078 BigO(char const* bigOName, RangeMeasure const& rangeMeasure, Op rangeToN)
1079 : BigO(bigOName, mapRangeMeasure(rangeMeasure, rangeToN)) {}
1080
1081 template <typename Op>
1082 BigO(std::string const& bigOName, RangeMeasure const& rangeMeasure, Op rangeToN)
1083 : BigO(bigOName, mapRangeMeasure(rangeMeasure, rangeToN)) {}
1084
1085 BigO(char const* bigOName, RangeMeasure const& scaledRangeMeasure);
1086 BigO(std::string const& bigOName, RangeMeasure const& scaledRangeMeasure);
1087 ANKERL_NANOBENCH(NODISCARD) std::string const& name() const noexcept;
1088 ANKERL_NANOBENCH(NODISCARD) double constant() const noexcept;
1089 ANKERL_NANOBENCH(NODISCARD) double normalizedRootMeanSquare() const noexcept;
1090 ANKERL_NANOBENCH(NODISCARD) bool operator<(BigO const& other) const noexcept;
1091
1092 private:
1093 std::string mName{};
1094 double mConstant{};
1095 double mNormalizedRootMeanSquare{};
1096 };
1097 std::ostream& operator<<(std::ostream& os, BigO const& bigO);
1098 std::ostream& operator<<(std::ostream& os, std::vector<ankerl::nanobench::BigO> const& bigOs);
1099
1100 } // namespace nanobench
1101 } // namespace ankerl
1102
1103 // implementation /////////////////////////////////////////////////////////////////////////////////
1104
1105 namespace ankerl {
1106 namespace nanobench {
1107
1108 constexpr uint64_t(Rng::min)() {
1109 return 0;
1110 }
1111
1112 constexpr uint64_t(Rng::max)() {
1113 return (std::numeric_limits<uint64_t>::max)();
1114 }
1115
1116 ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined")
1117 uint64_t Rng::operator()() noexcept {
1118 auto x = mX;
1119
1120 mX = UINT64_C(15241094284759029579) * mY;
1121 mY = rotl(mY - x, 27);
1122
1123 return x;
1124 }
1125
1126 ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined")
1127 uint32_t Rng::bounded(uint32_t range) noexcept {
1128 uint64_t r32 = static_cast<uint32_t>(operator()());
1129 auto multiresult = r32 * range;
1130 return static_cast<uint32_t>(multiresult >> 32U);
1131 }
1132
1133 double Rng::uniform01() noexcept {
1134 auto i = (UINT64_C(0x3ff) << 52U) | (operator()() >> 12U);
1135 // can't use union in c++ here for type puning, it's undefined behavior.
1136 // std::memcpy is optimized anyways.
1137 double d;
1138 std::memcpy(&d, &i, sizeof(double));
1139 return d - 1.0;
1140 }
1141
1142 template <typename Container>
1143 void Rng::shuffle(Container& container) noexcept {
1144 auto size = static_cast<uint32_t>(container.size());
1145 for (auto i = size; i > 1U; --i) {
1146 using std::swap;
1147 auto p = bounded(i); // number in [0, i)
1148 swap(container[i - 1], container[p]);
1149 }
1150 }
1151
1152 constexpr uint64_t Rng::rotl(uint64_t x, unsigned k) noexcept {
1153 return (x << k) | (x >> (64U - k));
1154 }
1155
1156 template <typename Op>
1157 ANKERL_NANOBENCH_NO_SANITIZE("integer")
1158 Bench& Bench::run(Op&& op) {
1159 // It is important that this method is kept short so the compiler can do better optimizations/ inlining of op()
1160 detail::IterationLogic iterationLogic(*this);
1161 auto& pc = detail::performanceCounters();
1162
1163 while (auto n = iterationLogic.numIters()) {
1164 pc.beginMeasure();
1165 Clock::time_point before = Clock::now();
1166 while (n-- > 0) {
1167 op();
1168 }
1169 Clock::time_point after = Clock::now();
1170 pc.endMeasure();
1171 pc.updateResults(iterationLogic.numIters());
1172 iterationLogic.add(after - before, pc);
1173 }
1174 iterationLogic.moveResultTo(mResults);
1175 return *this;
1176 }
1177
1178 // Performs all evaluations.
1179 template <typename Op>
1180 Bench& Bench::run(char const* benchmarkName, Op&& op) {
1181 name(benchmarkName);
1182 return run(std::forward<Op>(op));
1183 }
1184
1185 template <typename Op>
1186 Bench& Bench::run(std::string const& benchmarkName, Op&& op) {
1187 name(benchmarkName);
1188 return run(std::forward<Op>(op));
1189 }
1190
1191 template <typename Op>
1192 BigO Bench::complexityBigO(char const* benchmarkName, Op op) const {
1193 return BigO(benchmarkName, BigO::collectRangeMeasure(mResults), op);
1194 }
1195
1196 template <typename Op>
1197 BigO Bench::complexityBigO(std::string const& benchmarkName, Op op) const {
1198 return BigO(benchmarkName, BigO::collectRangeMeasure(mResults), op);
1199 }
1200
1201 // Set the batch size, e.g. number of processed bytes, or some other metric for the size of the processed data in each iteration.
1202 // Any argument is cast to double.
1203 template <typename T>
1204 Bench& Bench::batch(T b) noexcept {
1205 mConfig.mBatch = static_cast<double>(b);
1206 return *this;
1207 }
1208
1209 // Sets the computation complexity of the next run. Any argument is cast to double.
1210 template <typename T>
1211 Bench& Bench::complexityN(T n) noexcept {
1212 mConfig.mComplexityN = static_cast<double>(n);
1213 return *this;
1214 }
1215
1216 // Convenience: makes sure none of the given arguments are optimized away by the compiler.
1217 template <typename Arg>
1218 Bench& Bench::doNotOptimizeAway(Arg&& arg) {
1219 detail::doNotOptimizeAway(std::forward<Arg>(arg));
1220 return *this;
1221 }
1222
1223 // Makes sure none of the given arguments are optimized away by the compiler.
1224 template <typename Arg>
1225 void doNotOptimizeAway(Arg&& arg) {
1226 detail::doNotOptimizeAway(std::forward<Arg>(arg));
1227 }
1228
1229 namespace detail {
1230
1231 #if defined(_MSC_VER)
1232 template <typename T>
1233 void doNotOptimizeAway(T const& val) {
1234 doNotOptimizeAwaySink(&val);
1235 }
1236
1237 #endif
1238
1239 } // namespace detail
1240 } // namespace nanobench
1241 } // namespace ankerl
1242
1243 #if defined(ANKERL_NANOBENCH_IMPLEMENT)
1244
1245 ///////////////////////////////////////////////////////////////////////////////////////////////////
1246 // implementation part - only visible in .cpp
1247 ///////////////////////////////////////////////////////////////////////////////////////////////////
1248
1249 # include <algorithm> // sort, reverse
1250 # include <atomic> // compare_exchange_strong in loop overhead
1251 # include <cstdlib> // getenv
1252 # include <cstring> // strstr, strncmp
1253 # include <fstream> // ifstream to parse proc files
1254 # include <iomanip> // setw, setprecision
1255 # include <iostream> // cout
1256 # include <numeric> // accumulate
1257 # include <random> // random_device
1258 # include <sstream> // to_s in Number
1259 # include <stdexcept> // throw for rendering templates
1260 # include <tuple> // std::tie
1261 # if defined(__linux__)
1262 # include <unistd.h> //sysconf
1263 # endif
1264 # if ANKERL_NANOBENCH(PERF_COUNTERS)
1265 # include <map> // map
1266
1267 # include <linux/perf_event.h>
1268 # include <sys/ioctl.h>
1269 # include <sys/syscall.h>
1270 # include <unistd.h>
1271 # endif
1272
1273 // declarations ///////////////////////////////////////////////////////////////////////////////////
1274
1275 namespace ankerl {
1276 namespace nanobench {
1277
1278 // helper stuff that is only intended to be used internally
1279 namespace detail {
1280
1281 struct TableInfo;
1282
1283 // formatting utilities
1284 namespace fmt {
1285
1286 class NumSep;
1287 class StreamStateRestorer;
1288 class Number;
1289 class MarkDownColumn;
1290 class MarkDownCode;
1291
1292 } // namespace fmt
1293 } // namespace detail
1294 } // namespace nanobench
1295 } // namespace ankerl
1296
1297 // definitions ////////////////////////////////////////////////////////////////////////////////////
1298
1299 namespace ankerl {
1300 namespace nanobench {
1301
1302 uint64_t splitMix64(uint64_t& state) noexcept;
1303
1304 namespace detail {
1305
1306 // helpers to get double values
1307 template <typename T>
1308 inline double d(T t) noexcept {
1309 return static_cast<double>(t);
1310 }
1311 inline double d(Clock::duration duration) noexcept {
1312 return std::chrono::duration_cast<std::chrono::duration<double>>(duration).count();
1313 }
1314
1315 // Calculates clock resolution once, and remembers the result
1316 inline Clock::duration clockResolution() noexcept;
1317
1318 } // namespace detail
1319
1320 namespace templates {
1321
1322 char const* csv() noexcept {
1323 return R"DELIM("title";"name";"unit";"batch";"elapsed";"error %";"instructions";"branches";"branch misses";"total"
1324 {{#result}}"{{title}}";"{{name}}";"{{unit}}";{{batch}};{{median(elapsed)}};{{medianAbsolutePercentError(elapsed)}};{{median(instructions)}};{{median(branchinstructions)}};{{median(branchmisses)}};{{sumProduct(iterations, elapsed)}}
1325 {{/result}})DELIM";
1326 }
1327
1328 char const* htmlBoxplot() noexcept {
1329 return R"DELIM(<html>
1330
1331 <head>
1332 <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
1333 </head>
1334
1335 <body>
1336 <div id="myDiv"></div>
1337 <script>
1338 var data = [
1339 {{#result}}{
1340 name: '{{name}}',
1341 y: [{{#measurement}}{{elapsed}}{{^-last}}, {{/last}}{{/measurement}}],
1342 },
1343 {{/result}}
1344 ];
1345 var title = '{{title}}';
1346
1347 data = data.map(a => Object.assign(a, { boxpoints: 'all', pointpos: 0, type: 'box' }));
1348 var layout = { title: { text: title }, showlegend: false, yaxis: { title: 'time per unit', rangemode: 'tozero', autorange: true } }; Plotly.newPlot('myDiv', data, layout, {responsive: true});
1349 </script>
1350 </body>
1351
1352 </html>)DELIM";
1353 }
1354
1355 char const* pyperf() noexcept {
1356 return R"DELIM({
1357 "benchmarks": [
1358 {
1359 "runs": [
1360 {
1361 "values": [
1362 {{#measurement}} {{elapsed}}{{^-last}},
1363 {{/last}}{{/measurement}}
1364 ]
1365 }
1366 ]
1367 }
1368 ],
1369 "metadata": {
1370 "loops": {{sum(iterations)}},
1371 "inner_loops": {{batch}},
1372 "name": "{{title}}",
1373 "unit": "second"
1374 },
1375 "version": "1.0"
1376 })DELIM";
1377 }
1378
1379 char const* json() noexcept {
1380 return R"DELIM({
1381 "results": [
1382 {{#result}} {
1383 "title": "{{title}}",
1384 "name": "{{name}}",
1385 "unit": "{{unit}}",
1386 "batch": {{batch}},
1387 "complexityN": {{complexityN}},
1388 "epochs": {{epochs}},
1389 "clockResolution": {{clockResolution}},
1390 "clockResolutionMultiple": {{clockResolutionMultiple}},
1391 "maxEpochTime": {{maxEpochTime}},
1392 "minEpochTime": {{minEpochTime}},
1393 "minEpochIterations": {{minEpochIterations}},
1394 "epochIterations": {{epochIterations}},
1395 "warmup": {{warmup}},
1396 "relative": {{relative}},
1397 "median(elapsed)": {{median(elapsed)}},
1398 "medianAbsolutePercentError(elapsed)": {{medianAbsolutePercentError(elapsed)}},
1399 "median(instructions)": {{median(instructions)}},
1400 "medianAbsolutePercentError(instructions)": {{medianAbsolutePercentError(instructions)}},
1401 "median(cpucycles)": {{median(cpucycles)}},
1402 "median(contextswitches)": {{median(contextswitches)}},
1403 "median(pagefaults)": {{median(pagefaults)}},
1404 "median(branchinstructions)": {{median(branchinstructions)}},
1405 "median(branchmisses)": {{median(branchmisses)}},
1406 "totalTime": {{sumProduct(iterations, elapsed)}},
1407 "measurements": [
1408 {{#measurement}} {
1409 "iterations": {{iterations}},
1410 "elapsed": {{elapsed}},
1411 "pagefaults": {{pagefaults}},
1412 "cpucycles": {{cpucycles}},
1413 "contextswitches": {{contextswitches}},
1414 "instructions": {{instructions}},
1415 "branchinstructions": {{branchinstructions}},
1416 "branchmisses": {{branchmisses}}
1417 }{{^-last}},{{/-last}}
1418 {{/measurement}} ]
1419 }{{^-last}},{{/-last}}
1420 {{/result}} ]
1421 })DELIM";
1422 }
1423
1424 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
1425 struct Node {
1426 enum class Type { tag, content, section, inverted_section };
1427
1428 char const* begin;
1429 char const* end;
1430 std::vector<Node> children;
1431 Type type;
1432
1433 template <size_t N>
1434 // NOLINTNEXTLINE(hicpp-avoid-c-arrays,modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
1435 bool operator==(char const (&str)[N]) const noexcept {
1436 return static_cast<size_t>(std::distance(begin, end) + 1) == N && 0 == strncmp(str, begin, N - 1);
1437 }
1438 };
1439 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
1440
1441 static std::vector<Node> parseMustacheTemplate(char const** tpl) {
1442 std::vector<Node> nodes;
1443
1444 while (true) {
1445 auto begin = std::strstr(*tpl, "{{");
1446 auto end = begin;
1447 if (begin != nullptr) {
1448 begin += 2;
1449 end = std::strstr(begin, "}}");
1450 }
1451
1452 if (begin == nullptr || end == nullptr) {
1453 // nothing found, finish node
1454 nodes.emplace_back(Node{*tpl, *tpl + std::strlen(*tpl), std::vector<Node>{}, Node::Type::content});
1455 return nodes;
1456 }
1457
1458 nodes.emplace_back(Node{*tpl, begin - 2, std::vector<Node>{}, Node::Type::content});
1459
1460 // we found a tag
1461 *tpl = end + 2;
1462 switch (*begin) {
1463 case '/':
1464 // finished! bail out
1465 return nodes;
1466
1467 case '#':
1468 nodes.emplace_back(Node{begin + 1, end, parseMustacheTemplate(tpl), Node::Type::section});
1469 break;
1470
1471 case '^':
1472 nodes.emplace_back(Node{begin + 1, end, parseMustacheTemplate(tpl), Node::Type::inverted_section});
1473 break;
1474
1475 default:
1476 nodes.emplace_back(Node{begin, end, std::vector<Node>{}, Node::Type::tag});
1477 break;
1478 }
1479 }
1480 }
1481
1482 static bool generateFirstLast(Node const& n, size_t idx, size_t size, std::ostream& out) {
1483 ANKERL_NANOBENCH_LOG("n.type=" << static_cast<int>(n.type));
1484 bool matchFirst = n == "-first";
1485 bool matchLast = n == "-last";
1486 if (!matchFirst && !matchLast) {
1487 return false;
1488 }
1489
1490 bool doWrite = false;
1491 if (n.type == Node::Type::section) {
1492 doWrite = (matchFirst && idx == 0) || (matchLast && idx == size - 1);
1493 } else if (n.type == Node::Type::inverted_section) {
1494 doWrite = (matchFirst && idx != 0) || (matchLast && idx != size - 1);
1495 }
1496
1497 if (doWrite) {
1498 for (auto const& child : n.children) {
1499 if (child.type == Node::Type::content) {
1500 out.write(child.begin, std::distance(child.begin, child.end));
1501 }
1502 }
1503 }
1504 return true;
1505 }
1506
1507 static bool matchCmdArgs(std::string const& str, std::vector<std::string>& matchResult) {
1508 matchResult.clear();
1509 auto idxOpen = str.find('(');
1510 auto idxClose = str.find(')', idxOpen);
1511 if (idxClose == std::string::npos) {
1512 return false;
1513 }
1514
1515 matchResult.emplace_back(str.substr(0, idxOpen));
1516
1517 // split by comma
1518 matchResult.emplace_back(std::string{});
1519 for (size_t i = idxOpen + 1; i != idxClose; ++i) {
1520 if (str[i] == ' ' || str[i] == '\t') {
1521 // skip whitespace
1522 continue;
1523 }
1524 if (str[i] == ',') {
1525 // got a comma => new string
1526 matchResult.emplace_back(std::string{});
1527 continue;
1528 }
1529 // no whitespace no comma, append
1530 matchResult.back() += str[i];
1531 }
1532 return true;
1533 }
1534
1535 static bool generateConfigTag(Node const& n, Config const& config, std::ostream& out) {
1536 using detail::d;
1537
1538 if (n == "title") {
1539 out << config.mBenchmarkTitle;
1540 return true;
1541 } else if (n == "name") {
1542 out << config.mBenchmarkName;
1543 return true;
1544 } else if (n == "unit") {
1545 out << config.mUnit;
1546 return true;
1547 } else if (n == "batch") {
1548 out << config.mBatch;
1549 return true;
1550 } else if (n == "complexityN") {
1551 out << config.mComplexityN;
1552 return true;
1553 } else if (n == "epochs") {
1554 out << config.mNumEpochs;
1555 return true;
1556 } else if (n == "clockResolution") {
1557 out << d(detail::clockResolution());
1558 return true;
1559 } else if (n == "clockResolutionMultiple") {
1560 out << config.mClockResolutionMultiple;
1561 return true;
1562 } else if (n == "maxEpochTime") {
1563 out << d(config.mMaxEpochTime);
1564 return true;
1565 } else if (n == "minEpochTime") {
1566 out << d(config.mMinEpochTime);
1567 return true;
1568 } else if (n == "minEpochIterations") {
1569 out << config.mMinEpochIterations;
1570 return true;
1571 } else if (n == "epochIterations") {
1572 out << config.mEpochIterations;
1573 return true;
1574 } else if (n == "warmup") {
1575 out << config.mWarmup;
1576 return true;
1577 } else if (n == "relative") {
1578 out << config.mIsRelative;
1579 return true;
1580 }
1581 return false;
1582 }
1583
1584 static std::ostream& generateResultTag(Node const& n, Result const& r, std::ostream& out) {
1585 if (generateConfigTag(n, r.config(), out)) {
1586 return out;
1587 }
1588 // match e.g. "median(elapsed)"
1589 // g++ 4.8 doesn't implement std::regex :(
1590 // static std::regex const regOpArg1("^([a-zA-Z]+)\\(([a-zA-Z]*)\\)$");
1591 // std::cmatch matchResult;
1592 // if (std::regex_match(n.begin, n.end, matchResult, regOpArg1)) {
1593 std::vector<std::string> matchResult;
1594 if (matchCmdArgs(std::string(n.begin, n.end), matchResult)) {
1595 if (matchResult.size() == 2) {
1596 auto m = Result::fromString(matchResult[1]);
1597 if (m == Result::Measure::_size) {
1598 return out << 0.0;
1599 }
1600
1601 if (matchResult[0] == "median") {
1602 return out << r.median(m);
1603 }
1604 if (matchResult[0] == "average") {
1605 return out << r.average(m);
1606 }
1607 if (matchResult[0] == "medianAbsolutePercentError") {
1608 return out << r.medianAbsolutePercentError(m);
1609 }
1610 if (matchResult[0] == "sum") {
1611 return out << r.sum(m);
1612 }
1613 if (matchResult[0] == "minimum") {
1614 return out << r.minimum(m);
1615 }
1616 if (matchResult[0] == "maximum") {
1617 return out << r.maximum(m);
1618 }
1619 } else if (matchResult.size() == 3) {
1620 auto m1 = Result::fromString(matchResult[1]);
1621 auto m2 = Result::fromString(matchResult[2]);
1622 if (m1 == Result::Measure::_size || m2 == Result::Measure::_size) {
1623 return out << 0.0;
1624 }
1625
1626 if (matchResult[0] == "sumProduct") {
1627 return out << r.sumProduct(m1, m2);
1628 }
1629 }
1630 }
1631
1632 // match e.g. "sumProduct(elapsed, iterations)"
1633 // static std::regex const regOpArg2("^([a-zA-Z]+)\\(([a-zA-Z]*)\\s*,\\s+([a-zA-Z]*)\\)$");
1634
1635 // nothing matches :(
1636 throw std::runtime_error("command '" + std::string(n.begin, n.end) + "' not understood");
1637 }
1638
1639 static void generateResultMeasurement(std::vector<Node> const& nodes, size_t idx, Result const& r, std::ostream& out) {
1640 for (auto const& n : nodes) {
1641 if (!generateFirstLast(n, idx, r.size(), out)) {
1642 ANKERL_NANOBENCH_LOG("n.type=" << static_cast<int>(n.type));
1643 switch (n.type) {
1644 case Node::Type::content:
1645 out.write(n.begin, std::distance(n.begin, n.end));
1646 break;
1647
1648 case Node::Type::inverted_section:
1649 throw std::runtime_error("got a inverted section inside measurement");
1650
1651 case Node::Type::section:
1652 throw std::runtime_error("got a section inside measurement");
1653
1654 case Node::Type::tag: {
1655 auto m = Result::fromString(std::string(n.begin, n.end));
1656 if (m == Result::Measure::_size || !r.has(m)) {
1657 out << 0.0;
1658 } else {
1659 out << r.get(idx, m);
1660 }
1661 break;
1662 }
1663 }
1664 }
1665 }
1666 }
1667
1668 static void generateResult(std::vector<Node> const& nodes, size_t idx, std::vector<Result> const& results, std::ostream& out) {
1669 auto const& r = results[idx];
1670 for (auto const& n : nodes) {
1671 if (!generateFirstLast(n, idx, results.size(), out)) {
1672 ANKERL_NANOBENCH_LOG("n.type=" << static_cast<int>(n.type));
1673 switch (n.type) {
1674 case Node::Type::content:
1675 out.write(n.begin, std::distance(n.begin, n.end));
1676 break;
1677
1678 case Node::Type::inverted_section:
1679 throw std::runtime_error("got a inverted section inside result");
1680
1681 case Node::Type::section:
1682 if (n == "measurement") {
1683 for (size_t i = 0; i < r.size(); ++i) {
1684 generateResultMeasurement(n.children, i, r, out);
1685 }
1686 } else {
1687 throw std::runtime_error("got a section inside result");
1688 }
1689 break;
1690
1691 case Node::Type::tag:
1692 generateResultTag(n, r, out);
1693 break;
1694 }
1695 }
1696 }
1697 }
1698
1699 } // namespace templates
1700
1701 // helper stuff that only intended to be used internally
1702 namespace detail {
1703
1704 char const* getEnv(char const* name);
1705 bool isEndlessRunning(std::string const& name);
1706 bool isWarningsEnabled();
1707
1708 template <typename T>
1709 T parseFile(std::string const& filename);
1710
1711 void gatherStabilityInformation(std::vector<std::string>& warnings, std::vector<std::string>& recommendations);
1712 void printStabilityInformationOnce(std::ostream* os);
1713
1714 // remembers the last table settings used. When it changes, a new table header is automatically written for the new entry.
1715 uint64_t& singletonHeaderHash() noexcept;
1716
1717 // determines resolution of the given clock. This is done by measuring multiple times and returning the minimum time difference.
1718 Clock::duration calcClockResolution(size_t numEvaluations) noexcept;
1719
1720 // formatting utilities
1721 namespace fmt {
1722
1723 // adds thousands separator to numbers
1724 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
1725 class NumSep : public std::numpunct<char> {
1726 public:
1727 explicit NumSep(char sep);
1728 char do_thousands_sep() const override;
1729 std::string do_grouping() const override;
1730
1731 private:
1732 char mSep;
1733 };
1734 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
1735
1736 // RAII to save & restore a stream's state
1737 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
1738 class StreamStateRestorer {
1739 public:
1740 explicit StreamStateRestorer(std::ostream& s);
1741 ~StreamStateRestorer();
1742
1743 // sets back all stream info that we remembered at construction
1744 void restore();
1745
1746 // don't allow copying / moving
1747 StreamStateRestorer(StreamStateRestorer const&) = delete;
1748 StreamStateRestorer& operator=(StreamStateRestorer const&) = delete;
1749 StreamStateRestorer(StreamStateRestorer&&) = delete;
1750 StreamStateRestorer& operator=(StreamStateRestorer&&) = delete;
1751
1752 private:
1753 std::ostream& mStream;
1754 std::locale mLocale;
1755 std::streamsize const mPrecision;
1756 std::streamsize const mWidth;
1757 std::ostream::char_type const mFill;
1758 std::ostream::fmtflags const mFmtFlags;
1759 };
1760 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
1761
1762 // Number formatter
1763 class Number {
1764 public:
1765 Number(int width, int precision, double value);
1766 Number(int width, int precision, int64_t value);
1767 std::string to_s() const;
1768
1769 private:
1770 friend std::ostream& operator<<(std::ostream& os, Number const& n);
1771 std::ostream& write(std::ostream& os) const;
1772
1773 int mWidth;
1774 int mPrecision;
1775 double mValue;
1776 };
1777
1778 // helper replacement for std::to_string of signed/unsigned numbers so we are locale independent
1779 std::string to_s(uint64_t s);
1780
1781 std::ostream& operator<<(std::ostream& os, Number const& n);
1782
1783 class MarkDownColumn {
1784 public:
1785 MarkDownColumn(int w, int prec, std::string const& tit, std::string const& suff, double val);
1786 std::string title() const;
1787 std::string separator() const;
1788 std::string invalid() const;
1789 std::string value() const;
1790
1791 private:
1792 int mWidth;
1793 int mPrecision;
1794 std::string mTitle;
1795 std::string mSuffix;
1796 double mValue;
1797 };
1798
1799 // Formats any text as markdown code, escaping backticks.
1800 class MarkDownCode {
1801 public:
1802 explicit MarkDownCode(std::string const& what);
1803
1804 private:
1805 friend std::ostream& operator<<(std::ostream& os, MarkDownCode const& mdCode);
1806 std::ostream& write(std::ostream& os) const;
1807
1808 std::string mWhat{};
1809 };
1810
1811 std::ostream& operator<<(std::ostream& os, MarkDownCode const& mdCode);
1812
1813 } // namespace fmt
1814 } // namespace detail
1815 } // namespace nanobench
1816 } // namespace ankerl
1817
1818 // implementation /////////////////////////////////////////////////////////////////////////////////
1819
1820 namespace ankerl {
1821 namespace nanobench {
1822
1823 void render(char const* mustacheTemplate, std::vector<Result> const& results, std::ostream& out) {
1824 detail::fmt::StreamStateRestorer restorer(out);
1825
1826 out.precision(std::numeric_limits<double>::digits10);
1827 auto nodes = templates::parseMustacheTemplate(&mustacheTemplate);
1828
1829 for (auto const& n : nodes) {
1830 ANKERL_NANOBENCH_LOG("n.type=" << static_cast<int>(n.type));
1831 switch (n.type) {
1832 case templates::Node::Type::content:
1833 out.write(n.begin, std::distance(n.begin, n.end));
1834 break;
1835
1836 case templates::Node::Type::inverted_section:
1837 throw std::runtime_error("unknown list '" + std::string(n.begin, n.end) + "'");
1838
1839 case templates::Node::Type::section:
1840 if (n == "result") {
1841 const size_t nbResults = results.size();
1842 for (size_t i = 0; i < nbResults; ++i) {
1843 generateResult(n.children, i, results, out);
1844 }
1845 } else if (n == "measurement") {
1846 if (results.size() != 1) {
1847 throw std::runtime_error(
1848 "render: can only use section 'measurement' here if there is a single result, but there are " +
1849 detail::fmt::to_s(results.size()));
1850 }
1851 // when we only have a single result, we can immediately go into its measurement.
1852 auto const& r = results.front();
1853 for (size_t i = 0; i < r.size(); ++i) {
1854 generateResultMeasurement(n.children, i, r, out);
1855 }
1856 } else {
1857 throw std::runtime_error("render: unknown section '" + std::string(n.begin, n.end) + "'");
1858 }
1859 break;
1860
1861 case templates::Node::Type::tag:
1862 if (results.size() == 1) {
1863 // result & config are both supported there
1864 generateResultTag(n, results.front(), out);
1865 } else {
1866 // This just uses the last result's config.
1867 if (!generateConfigTag(n, results.back().config(), out)) {
1868 throw std::runtime_error("unknown tag '" + std::string(n.begin, n.end) + "'");
1869 }
1870 }
1871 break;
1872 }
1873 }
1874 }
1875
1876 void render(std::string const& mustacheTemplate, std::vector<Result> const& results, std::ostream& out) {
1877 render(mustacheTemplate.c_str(), results, out);
1878 }
1879
1880 void render(char const* mustacheTemplate, const Bench& bench, std::ostream& out) {
1881 render(mustacheTemplate, bench.results(), out);
1882 }
1883
1884 void render(std::string const& mustacheTemplate, const Bench& bench, std::ostream& out) {
1885 render(mustacheTemplate.c_str(), bench.results(), out);
1886 }
1887
1888 namespace detail {
1889
1890 PerformanceCounters& performanceCounters() {
1891 # if defined(__clang__)
1892 # pragma clang diagnostic push
1893 # pragma clang diagnostic ignored "-Wexit-time-destructors"
1894 # endif
1895 static PerformanceCounters pc;
1896 # if defined(__clang__)
1897 # pragma clang diagnostic pop
1898 # endif
1899 return pc;
1900 }
1901
1902 // Windows version of doNotOptimizeAway
1903 // see https://github.com/google/benchmark/blob/master/include/benchmark/benchmark.h#L307
1904 // see https://github.com/facebook/folly/blob/master/folly/Benchmark.h#L280
1905 // see https://docs.microsoft.com/en-us/cpp/preprocessor/optimize
1906 # if defined(_MSC_VER)
1907 # pragma optimize("", off)
1908 void doNotOptimizeAwaySink(void const*) {}
1909 # pragma optimize("", on)
1910 # endif
1911
1912 template <typename T>
1913 T parseFile(std::string const& filename) {
1914 std::ifstream fin(filename);
1915 T num{};
1916 fin >> num;
1917 return num;
1918 }
1919
1920 char const* getEnv(char const* name) {
1921 # if defined(_MSC_VER)
1922 # pragma warning(push)
1923 # pragma warning(disable : 4996) // getenv': This function or variable may be unsafe.
1924 # endif
1925 return std::getenv(name);
1926 # if defined(_MSC_VER)
1927 # pragma warning(pop)
1928 # endif
1929 }
1930
1931 bool isEndlessRunning(std::string const& name) {
1932 auto endless = getEnv("NANOBENCH_ENDLESS");
1933 return nullptr != endless && endless == name;
1934 }
1935
1936 // True when environment variable NANOBENCH_SUPPRESS_WARNINGS is either not set at all, or set to "0"
1937 bool isWarningsEnabled() {
1938 auto suppression = getEnv("NANOBENCH_SUPPRESS_WARNINGS");
1939 return nullptr == suppression || suppression == std::string("0");
1940 }
1941
1942 void gatherStabilityInformation(std::vector<std::string>& warnings, std::vector<std::string>& recommendations) {
1943 warnings.clear();
1944 recommendations.clear();
1945
1946 bool recommendCheckFlags = false;
1947
1948 # if defined(DEBUG)
1949 warnings.emplace_back("DEBUG defined");
1950 recommendCheckFlags = true;
1951 # endif
1952
1953 bool recommendPyPerf = false;
1954 # if defined(__linux__)
1955 auto nprocs = sysconf(_SC_NPROCESSORS_CONF);
1956 if (nprocs <= 0) {
1957 warnings.emplace_back("couldn't figure out number of processors - no governor, turbo check possible");
1958 } else {
1959
1960 // check frequency scaling
1961 for (long id = 0; id < nprocs; ++id) {
1962 auto idStr = detail::fmt::to_s(static_cast<uint64_t>(id));
1963 auto sysCpu = "/sys/devices/system/cpu/cpu" + idStr;
1964 auto minFreq = parseFile<int64_t>(sysCpu + "/cpufreq/scaling_min_freq");
1965 auto maxFreq = parseFile<int64_t>(sysCpu + "/cpufreq/scaling_max_freq");
1966 if (minFreq != maxFreq) {
1967 auto minMHz = static_cast<double>(minFreq) / 1000.0;
1968 auto maxMHz = static_cast<double>(maxFreq) / 1000.0;
1969 warnings.emplace_back("CPU frequency scaling enabled: CPU " + idStr + " between " +
1970 detail::fmt::Number(1, 1, minMHz).to_s() + " and " + detail::fmt::Number(1, 1, maxMHz).to_s() +
1971 " MHz");
1972 recommendPyPerf = true;
1973 break;
1974 }
1975 }
1976
1977 auto currentGovernor = parseFile<std::string>("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor");
1978 if ("performance" != currentGovernor) {
1979 warnings.emplace_back("CPU governor is '" + currentGovernor + "' but should be 'performance'");
1980 recommendPyPerf = true;
1981 }
1982
1983 if (0 == parseFile<int>("/sys/devices/system/cpu/intel_pstate/no_turbo")) {
1984 warnings.emplace_back("Turbo is enabled, CPU frequency will fluctuate");
1985 recommendPyPerf = true;
1986 }
1987 }
1988 # endif
1989
1990 if (recommendCheckFlags) {
1991 recommendations.emplace_back("Make sure you compile for Release");
1992 }
1993 if (recommendPyPerf) {
1994 recommendations.emplace_back("Use 'pyperf system tune' before benchmarking. See https://github.com/psf/pyperf");
1995 }
1996 }
1997
1998 void printStabilityInformationOnce(std::ostream* outStream) {
1999 static bool shouldPrint = true;
2000 if (shouldPrint && outStream && isWarningsEnabled()) {
2001 auto& os = *outStream;
2002 shouldPrint = false;
2003 std::vector<std::string> warnings;
2004 std::vector<std::string> recommendations;
2005 gatherStabilityInformation(warnings, recommendations);
2006 if (warnings.empty()) {
2007 return;
2008 }
2009
2010 os << "Warning, results might be unstable:" << std::endl;
2011 for (auto const& w : warnings) {
2012 os << "* " << w << std::endl;
2013 }
2014
2015 os << std::endl << "Recommendations" << std::endl;
2016 for (auto const& r : recommendations) {
2017 os << "* " << r << std::endl;
2018 }
2019 }
2020 }
2021
2022 // remembers the last table settings used. When it changes, a new table header is automatically written for the new entry.
2023 uint64_t& singletonHeaderHash() noexcept {
2024 static uint64_t sHeaderHash{};
2025 return sHeaderHash;
2026 }
2027
2028 ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined")
2029 inline uint64_t hash_combine(uint64_t seed, uint64_t val) {
2030 return seed ^ (val + UINT64_C(0x9e3779b9) + (seed << 6U) + (seed >> 2U));
2031 }
2032
2033 // determines resolution of the given clock. This is done by measuring multiple times and returning the minimum time difference.
2034 Clock::duration calcClockResolution(size_t numEvaluations) noexcept {
2035 auto bestDuration = Clock::duration::max();
2036 Clock::time_point tBegin;
2037 Clock::time_point tEnd;
2038 for (size_t i = 0; i < numEvaluations; ++i) {
2039 tBegin = Clock::now();
2040 do {
2041 tEnd = Clock::now();
2042 } while (tBegin == tEnd);
2043 bestDuration = (std::min)(bestDuration, tEnd - tBegin);
2044 }
2045 return bestDuration;
2046 }
2047
2048 // Calculates clock resolution once, and remembers the result
2049 Clock::duration clockResolution() noexcept {
2050 static Clock::duration sResolution = calcClockResolution(20);
2051 return sResolution;
2052 }
2053
2054 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
2055 struct IterationLogic::Impl {
2056 enum class State { warmup, upscaling_runtime, measuring, endless };
2057
2058 explicit Impl(Bench const& bench)
2059 : mBench(bench)
2060 , mResult(bench.config()) {
2061 printStabilityInformationOnce(mBench.output());
2062
2063 // determine target runtime per epoch
2064 mTargetRuntimePerEpoch = detail::clockResolution() * mBench.clockResolutionMultiple();
2065 if (mTargetRuntimePerEpoch > mBench.maxEpochTime()) {
2066 mTargetRuntimePerEpoch = mBench.maxEpochTime();
2067 }
2068 if (mTargetRuntimePerEpoch < mBench.minEpochTime()) {
2069 mTargetRuntimePerEpoch = mBench.minEpochTime();
2070 }
2071
2072 if (isEndlessRunning(mBench.name())) {
2073 std::cerr << "NANOBENCH_ENDLESS set: running '" << mBench.name() << "' endlessly" << std::endl;
2074 mNumIters = (std::numeric_limits<uint64_t>::max)();
2075 mState = State::endless;
2076 } else if (0 != mBench.warmup()) {
2077 mNumIters = mBench.warmup();
2078 mState = State::warmup;
2079 } else if (0 != mBench.epochIterations()) {
2080 // exact number of iterations
2081 mNumIters = mBench.epochIterations();
2082 mState = State::measuring;
2083 } else {
2084 mNumIters = mBench.minEpochIterations();
2085 mState = State::upscaling_runtime;
2086 }
2087 }
2088
2089 // directly calculates new iters based on elapsed&iters, and adds a 10% noise. Makes sure we don't underflow.
2090 ANKERL_NANOBENCH(NODISCARD) uint64_t calcBestNumIters(std::chrono::nanoseconds elapsed, uint64_t iters) noexcept {
2091 auto doubleElapsed = d(elapsed);
2092 auto doubleTargetRuntimePerEpoch = d(mTargetRuntimePerEpoch);
2093 auto doubleNewIters = doubleTargetRuntimePerEpoch / doubleElapsed * d(iters);
2094
2095 auto doubleMinEpochIters = d(mBench.minEpochIterations());
2096 if (doubleNewIters < doubleMinEpochIters) {
2097 doubleNewIters = doubleMinEpochIters;
2098 }
2099 doubleNewIters *= 1.0 + 0.2 * mRng.uniform01();
2100
2101 // +0.5 for correct rounding when casting
2102 // NOLINTNEXTLINE(bugprone-incorrect-roundings)
2103 return static_cast<uint64_t>(doubleNewIters + 0.5);
2104 }
2105
2106 ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined") void upscale(std::chrono::nanoseconds elapsed) {
2107 if (elapsed * 10 < mTargetRuntimePerEpoch) {
2108 // we are far below the target runtime. Multiply iterations by 10 (with overflow check)
2109 if (mNumIters * 10 < mNumIters) {
2110 // overflow :-(
2111 showResult("iterations overflow. Maybe your code got optimized away?");
2112 mNumIters = 0;
2113 return;
2114 }
2115 mNumIters *= 10;
2116 } else {
2117 mNumIters = calcBestNumIters(elapsed, mNumIters);
2118 }
2119 }
2120
2121 void add(std::chrono::nanoseconds elapsed, PerformanceCounters const& pc) noexcept {
2122 # if defined(ANKERL_NANOBENCH_LOG_ENABLED)
2123 auto oldIters = mNumIters;
2124 # endif
2125
2126 switch (mState) {
2127 case State::warmup:
2128 if (isCloseEnoughForMeasurements(elapsed)) {
2129 // if elapsed is close enough, we can skip upscaling and go right to measurements
2130 // still, we don't add the result to the measurements.
2131 mState = State::measuring;
2132 mNumIters = calcBestNumIters(elapsed, mNumIters);
2133 } else {
2134 // not close enough: switch to upscaling
2135 mState = State::upscaling_runtime;
2136 upscale(elapsed);
2137 }
2138 break;
2139
2140 case State::upscaling_runtime:
2141 if (isCloseEnoughForMeasurements(elapsed)) {
2142 // if we are close enough, add measurement and switch to always measuring
2143 mState = State::measuring;
2144 mTotalElapsed += elapsed;
2145 mTotalNumIters += mNumIters;
2146 mResult.add(elapsed, mNumIters, pc);
2147 mNumIters = calcBestNumIters(mTotalElapsed, mTotalNumIters);
2148 } else {
2149 upscale(elapsed);
2150 }
2151 break;
2152
2153 case State::measuring:
2154 // just add measurements - no questions asked. Even when runtime is low. But we can't ignore
2155 // that fluctuation, or else we would bias the result
2156 mTotalElapsed += elapsed;
2157 mTotalNumIters += mNumIters;
2158 mResult.add(elapsed, mNumIters, pc);
2159 if (0 != mBench.epochIterations()) {
2160 mNumIters = mBench.epochIterations();
2161 } else {
2162 mNumIters = calcBestNumIters(mTotalElapsed, mTotalNumIters);
2163 }
2164 break;
2165
2166 case State::endless:
2167 mNumIters = (std::numeric_limits<uint64_t>::max)();
2168 break;
2169 }
2170
2171 if (static_cast<uint64_t>(mResult.size()) == mBench.epochs()) {
2172 // we got all the results that we need, finish it
2173 showResult("");
2174 mNumIters = 0;
2175 }
2176
2177 ANKERL_NANOBENCH_LOG(mBench.name() << ": " << detail::fmt::Number(20, 3, static_cast<double>(elapsed.count())) << " elapsed, "
2178 << detail::fmt::Number(20, 3, static_cast<double>(mTargetRuntimePerEpoch.count()))
2179 << " target. oldIters=" << oldIters << ", mNumIters=" << mNumIters
2180 << ", mState=" << static_cast<int>(mState));
2181 }
2182
2183 void showResult(std::string const& errorMessage) const {
2184 ANKERL_NANOBENCH_LOG(errorMessage);
2185
2186 if (mBench.output() != nullptr) {
2187 // prepare column data ///////
2188 std::vector<fmt::MarkDownColumn> columns;
2189
2190 auto rMedian = mResult.median(Result::Measure::elapsed);
2191
2192 if (mBench.relative()) {
2193 double d = 100.0;
2194 if (!mBench.results().empty()) {
2195 d = rMedian <= 0.0 ? 0.0 : mBench.results().front().median(Result::Measure::elapsed) / rMedian * 100.0;
2196 }
2197 columns.emplace_back(11, 1, "relative", "%", d);
2198 }
2199
2200 if (mBench.complexityN() > 0) {
2201 columns.emplace_back(14, 0, "complexityN", "", mBench.complexityN());
2202 }
2203
2204 columns.emplace_back(22, 2, mBench.timeUnitName() + "/" + mBench.unit(), "",
2205 rMedian / (mBench.timeUnit().count() * mBench.batch()));
2206 columns.emplace_back(22, 2, mBench.unit() + "/s", "", rMedian <= 0.0 ? 0.0 : mBench.batch() / rMedian);
2207
2208 double rErrorMedian = mResult.medianAbsolutePercentError(Result::Measure::elapsed);
2209 columns.emplace_back(10, 1, "err%", "%", rErrorMedian * 100.0);
2210
2211 double rInsMedian = -1.0;
2212 if (mResult.has(Result::Measure::instructions)) {
2213 rInsMedian = mResult.median(Result::Measure::instructions);
2214 columns.emplace_back(18, 2, "ins/" + mBench.unit(), "", rInsMedian / mBench.batch());
2215 }
2216
2217 double rCycMedian = -1.0;
2218 if (mResult.has(Result::Measure::cpucycles)) {
2219 rCycMedian = mResult.median(Result::Measure::cpucycles);
2220 columns.emplace_back(18, 2, "cyc/" + mBench.unit(), "", rCycMedian / mBench.batch());
2221 }
2222 if (rInsMedian > 0.0 && rCycMedian > 0.0) {
2223 columns.emplace_back(9, 3, "IPC", "", rCycMedian <= 0.0 ? 0.0 : rInsMedian / rCycMedian);
2224 }
2225 if (mResult.has(Result::Measure::branchinstructions)) {
2226 double rBraMedian = mResult.median(Result::Measure::branchinstructions);
2227 columns.emplace_back(17, 2, "bra/" + mBench.unit(), "", rBraMedian / mBench.batch());
2228 if (mResult.has(Result::Measure::branchmisses)) {
2229 double p = 0.0;
2230 if (rBraMedian >= 1e-9) {
2231 p = 100.0 * mResult.median(Result::Measure::branchmisses) / rBraMedian;
2232 }
2233 columns.emplace_back(10, 1, "miss%", "%", p);
2234 }
2235 }
2236
2237 columns.emplace_back(12, 2, "total", "", mResult.sumProduct(Result::Measure::iterations, Result::Measure::elapsed));
2238
2239 // write everything
2240 auto& os = *mBench.output();
2241
2242 // combine all elements that are relevant for printing the header
2243 uint64_t hash = 0;
2244 hash = hash_combine(std::hash<std::string>{}(mBench.unit()), hash);
2245 hash = hash_combine(std::hash<std::string>{}(mBench.title()), hash);
2246 hash = hash_combine(std::hash<std::string>{}(mBench.timeUnitName()), hash);
2247 hash = hash_combine(std::hash<double>{}(mBench.timeUnit().count()), hash);
2248 hash = hash_combine(std::hash<bool>{}(mBench.relative()), hash);
2249 hash = hash_combine(std::hash<bool>{}(mBench.performanceCounters()), hash);
2250
2251 if (hash != singletonHeaderHash()) {
2252 singletonHeaderHash() = hash;
2253
2254 // no result yet, print header
2255 os << std::endl;
2256 for (auto const& col : columns) {
2257 os << col.title();
2258 }
2259 os << "| " << mBench.title() << std::endl;
2260
2261 for (auto const& col : columns) {
2262 os << col.separator();
2263 }
2264 os << "|:" << std::string(mBench.title().size() + 1U, '-') << std::endl;
2265 }
2266
2267 if (!errorMessage.empty()) {
2268 for (auto const& col : columns) {
2269 os << col.invalid();
2270 }
2271 os << "| :boom: " << fmt::MarkDownCode(mBench.name()) << " (" << errorMessage << ')' << std::endl;
2272 } else {
2273 for (auto const& col : columns) {
2274 os << col.value();
2275 }
2276 os << "| ";
2277 auto showUnstable = isWarningsEnabled() && rErrorMedian >= 0.05;
2278 if (showUnstable) {
2279 os << ":wavy_dash: ";
2280 }
2281 os << fmt::MarkDownCode(mBench.name());
2282 if (showUnstable) {
2283 auto avgIters = static_cast<double>(mTotalNumIters) / static_cast<double>(mBench.epochs());
2284 // NOLINTNEXTLINE(bugprone-incorrect-roundings)
2285 auto suggestedIters = static_cast<uint64_t>(avgIters * 10 + 0.5);
2286
2287 os << " (Unstable with ~" << detail::fmt::Number(1, 1, avgIters)
2288 << " iters. Increase `minEpochIterations` to e.g. " << suggestedIters << ")";
2289 }
2290 os << std::endl;
2291 }
2292 }
2293 }
2294
2295 ANKERL_NANOBENCH(NODISCARD) bool isCloseEnoughForMeasurements(std::chrono::nanoseconds elapsed) const noexcept {
2296 return elapsed * 3 >= mTargetRuntimePerEpoch * 2;
2297 }
2298
2299 uint64_t mNumIters = 1;
2300 Bench const& mBench;
2301 std::chrono::nanoseconds mTargetRuntimePerEpoch{};
2302 Result mResult;
2303 Rng mRng{123};
2304 std::chrono::nanoseconds mTotalElapsed{};
2305 uint64_t mTotalNumIters = 0;
2306
2307 State mState = State::upscaling_runtime;
2308 };
2309 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
2310
2311 IterationLogic::IterationLogic(Bench const& bench) noexcept
2312 : mPimpl(new Impl(bench)) {}
2313
2314 IterationLogic::~IterationLogic() {
2315 if (mPimpl) {
2316 delete mPimpl;
2317 }
2318 }
2319
2320 uint64_t IterationLogic::numIters() const noexcept {
2321 ANKERL_NANOBENCH_LOG(mPimpl->mBench.name() << ": mNumIters=" << mPimpl->mNumIters);
2322 return mPimpl->mNumIters;
2323 }
2324
2325 void IterationLogic::add(std::chrono::nanoseconds elapsed, PerformanceCounters const& pc) noexcept {
2326 mPimpl->add(elapsed, pc);
2327 }
2328
2329 void IterationLogic::moveResultTo(std::vector<Result>& results) noexcept {
2330 results.emplace_back(std::move(mPimpl->mResult));
2331 }
2332
2333 # if ANKERL_NANOBENCH(PERF_COUNTERS)
2334
2335 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
2336 class LinuxPerformanceCounters {
2337 public:
2338 struct Target {
2339 Target(uint64_t* targetValue_, bool correctMeasuringOverhead_, bool correctLoopOverhead_)
2340 : targetValue(targetValue_)
2341 , correctMeasuringOverhead(correctMeasuringOverhead_)
2342 , correctLoopOverhead(correctLoopOverhead_) {}
2343
2344 uint64_t* targetValue{};
2345 bool correctMeasuringOverhead{};
2346 bool correctLoopOverhead{};
2347 };
2348
2349 ~LinuxPerformanceCounters();
2350
2351 // quick operation
2352 inline void start() {}
2353
2354 inline void stop() {}
2355
2356 bool monitor(perf_sw_ids swId, Target target);
2357 bool monitor(perf_hw_id hwId, Target target);
2358
2359 bool hasError() const noexcept {
2360 return mHasError;
2361 }
2362
2363 // Just reading data is faster than enable & disabling.
2364 // we subtract data ourselves.
2365 inline void beginMeasure() {
2366 if (mHasError) {
2367 return;
2368 }
2369
2370 // NOLINTNEXTLINE(hicpp-signed-bitwise)
2371 mHasError = -1 == ioctl(mFd, PERF_EVENT_IOC_RESET, PERF_IOC_FLAG_GROUP);
2372 if (mHasError) {
2373 return;
2374 }
2375
2376 // NOLINTNEXTLINE(hicpp-signed-bitwise)
2377 mHasError = -1 == ioctl(mFd, PERF_EVENT_IOC_ENABLE, PERF_IOC_FLAG_GROUP);
2378 }
2379
2380 inline void endMeasure() {
2381 if (mHasError) {
2382 return;
2383 }
2384
2385 // NOLINTNEXTLINE(hicpp-signed-bitwise)
2386 mHasError = (-1 == ioctl(mFd, PERF_EVENT_IOC_DISABLE, PERF_IOC_FLAG_GROUP));
2387 if (mHasError) {
2388 return;
2389 }
2390
2391 auto const numBytes = sizeof(uint64_t) * mCounters.size();
2392 auto ret = read(mFd, mCounters.data(), numBytes);
2393 mHasError = ret != static_cast<ssize_t>(numBytes);
2394 }
2395
2396 void updateResults(uint64_t numIters);
2397
2398 // rounded integer division
2399 template <typename T>
2400 static inline T divRounded(T a, T divisor) {
2401 return (a + divisor / 2) / divisor;
2402 }
2403
2404 template <typename Op>
2405 ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined")
2406 void calibrate(Op&& op) {
2407 // clear current calibration data,
2408 for (auto& v : mCalibratedOverhead) {
2409 v = UINT64_C(0);
2410 }
2411
2412 // create new calibration data
2413 auto newCalibration = mCalibratedOverhead;
2414 for (auto& v : newCalibration) {
2415 v = (std::numeric_limits<uint64_t>::max)();
2416 }
2417 for (size_t iter = 0; iter < 100; ++iter) {
2418 beginMeasure();
2419 op();
2420 endMeasure();
2421 if (mHasError) {
2422 return;
2423 }
2424
2425 for (size_t i = 0; i < newCalibration.size(); ++i) {
2426 auto diff = mCounters[i];
2427 if (newCalibration[i] > diff) {
2428 newCalibration[i] = diff;
2429 }
2430 }
2431 }
2432
2433 mCalibratedOverhead = std::move(newCalibration);
2434
2435 {
2436 // calibrate loop overhead. For branches & instructions this makes sense, not so much for everything else like cycles.
2437 // marsaglia's xorshift: mov, sal/shr, xor. Times 3.
2438 // This has the nice property that the compiler doesn't seem to be able to optimize multiple calls any further.
2439 // see https://godbolt.org/z/49RVQ5
2440 uint64_t const numIters = 100000U + (std::random_device{}() & 3);
2441 uint64_t n = numIters;
2442 uint32_t x = 1234567;
2443 auto fn = [&]() {
2444 x ^= x << 13;
2445 x ^= x >> 17;
2446 x ^= x << 5;
2447 };
2448
2449 beginMeasure();
2450 while (n-- > 0) {
2451 fn();
2452 }
2453 endMeasure();
2454 detail::doNotOptimizeAway(x);
2455 auto measure1 = mCounters;
2456
2457 n = numIters;
2458 beginMeasure();
2459 while (n-- > 0) {
2460 // we now run *twice* so we can easily calculate the overhead
2461 fn();
2462 fn();
2463 }
2464 endMeasure();
2465 detail::doNotOptimizeAway(x);
2466 auto measure2 = mCounters;
2467
2468 for (size_t i = 0; i < mCounters.size(); ++i) {
2469 // factor 2 because we have two instructions per loop
2470 auto m1 = measure1[i] > mCalibratedOverhead[i] ? measure1[i] - mCalibratedOverhead[i] : 0;
2471 auto m2 = measure2[i] > mCalibratedOverhead[i] ? measure2[i] - mCalibratedOverhead[i] : 0;
2472 auto overhead = m1 * 2 > m2 ? m1 * 2 - m2 : 0;
2473
2474 mLoopOverhead[i] = divRounded(overhead, numIters);
2475 }
2476 }
2477 }
2478
2479 private:
2480 bool monitor(uint32_t type, uint64_t eventid, Target target);
2481
2482 std::map<uint64_t, Target> mIdToTarget{};
2483
2484 // start with minimum size of 3 for read_format
2485 std::vector<uint64_t> mCounters{3};
2486 std::vector<uint64_t> mCalibratedOverhead{3};
2487 std::vector<uint64_t> mLoopOverhead{3};
2488
2489 uint64_t mTimeEnabledNanos = 0;
2490 uint64_t mTimeRunningNanos = 0;
2491 int mFd = -1;
2492 bool mHasError = false;
2493 };
2494 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
2495
2496 LinuxPerformanceCounters::~LinuxPerformanceCounters() {
2497 if (-1 != mFd) {
2498 close(mFd);
2499 }
2500 }
2501
2502 bool LinuxPerformanceCounters::monitor(perf_sw_ids swId, LinuxPerformanceCounters::Target target) {
2503 return monitor(PERF_TYPE_SOFTWARE, swId, target);
2504 }
2505
2506 bool LinuxPerformanceCounters::monitor(perf_hw_id hwId, LinuxPerformanceCounters::Target target) {
2507 return monitor(PERF_TYPE_HARDWARE, hwId, target);
2508 }
2509
2510 // overflow is ok, it's checked
2511 ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined")
2512 void LinuxPerformanceCounters::updateResults(uint64_t numIters) {
2513 // clear old data
2514 for (auto& id_value : mIdToTarget) {
2515 *id_value.second.targetValue = UINT64_C(0);
2516 }
2517
2518 if (mHasError) {
2519 return;
2520 }
2521
2522 mTimeEnabledNanos = mCounters[1] - mCalibratedOverhead[1];
2523 mTimeRunningNanos = mCounters[2] - mCalibratedOverhead[2];
2524
2525 for (uint64_t i = 0; i < mCounters[0]; ++i) {
2526 auto idx = static_cast<size_t>(3 + i * 2 + 0);
2527 auto id = mCounters[idx + 1U];
2528
2529 auto it = mIdToTarget.find(id);
2530 if (it != mIdToTarget.end()) {
2531
2532 auto& tgt = it->second;
2533 *tgt.targetValue = mCounters[idx];
2534 if (tgt.correctMeasuringOverhead) {
2535 if (*tgt.targetValue >= mCalibratedOverhead[idx]) {
2536 *tgt.targetValue -= mCalibratedOverhead[idx];
2537 } else {
2538 *tgt.targetValue = 0U;
2539 }
2540 }
2541 if (tgt.correctLoopOverhead) {
2542 auto correctionVal = mLoopOverhead[idx] * numIters;
2543 if (*tgt.targetValue >= correctionVal) {
2544 *tgt.targetValue -= correctionVal;
2545 } else {
2546 *tgt.targetValue = 0U;
2547 }
2548 }
2549 }
2550 }
2551 }
2552
2553 bool LinuxPerformanceCounters::monitor(uint32_t type, uint64_t eventid, Target target) {
2554 *target.targetValue = (std::numeric_limits<uint64_t>::max)();
2555 if (mHasError) {
2556 return false;
2557 }
2558
2559 auto pea = perf_event_attr();
2560 std::memset(&pea, 0, sizeof(perf_event_attr));
2561 pea.type = type;
2562 pea.size = sizeof(perf_event_attr);
2563 pea.config = eventid;
2564 pea.disabled = 1; // start counter as disabled
2565 pea.exclude_kernel = 1;
2566 pea.exclude_hv = 1;
2567
2568 // NOLINTNEXTLINE(hicpp-signed-bitwise)
2569 pea.read_format = PERF_FORMAT_GROUP | PERF_FORMAT_ID | PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING;
2570
2571 const int pid = 0; // the current process
2572 const int cpu = -1; // all CPUs
2573 # if defined(PERF_FLAG_FD_CLOEXEC) // since Linux 3.14
2574 const unsigned long flags = PERF_FLAG_FD_CLOEXEC;
2575 # else
2576 const unsigned long flags = 0;
2577 # endif
2578
2579 auto fd = static_cast<int>(syscall(__NR_perf_event_open, &pea, pid, cpu, mFd, flags));
2580 if (-1 == fd) {
2581 return false;
2582 }
2583 if (-1 == mFd) {
2584 // first call: set to fd, and use this from now on
2585 mFd = fd;
2586 }
2587 uint64_t id = 0;
2588 // NOLINTNEXTLINE(hicpp-signed-bitwise)
2589 if (-1 == ioctl(fd, PERF_EVENT_IOC_ID, &id)) {
2590 // couldn't get id
2591 return false;
2592 }
2593
2594 // insert into map, rely on the fact that map's references are constant.
2595 mIdToTarget.emplace(id, target);
2596
2597 // prepare readformat with the correct size (after the insert)
2598 auto size = 3 + 2 * mIdToTarget.size();
2599 mCounters.resize(size);
2600 mCalibratedOverhead.resize(size);
2601 mLoopOverhead.resize(size);
2602
2603 return true;
2604 }
2605
2606 PerformanceCounters::PerformanceCounters()
2607 : mPc(new LinuxPerformanceCounters())
2608 , mVal()
2609 , mHas() {
2610
2611 mHas.pageFaults = mPc->monitor(PERF_COUNT_SW_PAGE_FAULTS, LinuxPerformanceCounters::Target(&mVal.pageFaults, true, false));
2612 mHas.cpuCycles = mPc->monitor(PERF_COUNT_HW_REF_CPU_CYCLES, LinuxPerformanceCounters::Target(&mVal.cpuCycles, true, false));
2613 mHas.contextSwitches =
2614 mPc->monitor(PERF_COUNT_SW_CONTEXT_SWITCHES, LinuxPerformanceCounters::Target(&mVal.contextSwitches, true, false));
2615 mHas.instructions = mPc->monitor(PERF_COUNT_HW_INSTRUCTIONS, LinuxPerformanceCounters::Target(&mVal.instructions, true, true));
2616 mHas.branchInstructions =
2617 mPc->monitor(PERF_COUNT_HW_BRANCH_INSTRUCTIONS, LinuxPerformanceCounters::Target(&mVal.branchInstructions, true, false));
2618 mHas.branchMisses = mPc->monitor(PERF_COUNT_HW_BRANCH_MISSES, LinuxPerformanceCounters::Target(&mVal.branchMisses, true, false));
2619 // mHas.branchMisses = false;
2620
2621 mPc->start();
2622 mPc->calibrate([] {
2623 auto before = ankerl::nanobench::Clock::now();
2624 auto after = ankerl::nanobench::Clock::now();
2625 (void)before;
2626 (void)after;
2627 });
2628
2629 if (mPc->hasError()) {
2630 // something failed, don't monitor anything.
2631 mHas = PerfCountSet<bool>{};
2632 }
2633 }
2634
2635 PerformanceCounters::~PerformanceCounters() {
2636 if (nullptr != mPc) {
2637 delete mPc;
2638 }
2639 }
2640
2641 void PerformanceCounters::beginMeasure() {
2642 mPc->beginMeasure();
2643 }
2644
2645 void PerformanceCounters::endMeasure() {
2646 mPc->endMeasure();
2647 }
2648
2649 void PerformanceCounters::updateResults(uint64_t numIters) {
2650 mPc->updateResults(numIters);
2651 }
2652
2653 # else
2654
2655 PerformanceCounters::PerformanceCounters() = default;
2656 PerformanceCounters::~PerformanceCounters() = default;
2657 void PerformanceCounters::beginMeasure() {}
2658 void PerformanceCounters::endMeasure() {}
2659 void PerformanceCounters::updateResults(uint64_t) {}
2660
2661 # endif
2662
2663 ANKERL_NANOBENCH(NODISCARD) PerfCountSet<uint64_t> const& PerformanceCounters::val() const noexcept {
2664 return mVal;
2665 }
2666 ANKERL_NANOBENCH(NODISCARD) PerfCountSet<bool> const& PerformanceCounters::has() const noexcept {
2667 return mHas;
2668 }
2669
2670 // formatting utilities
2671 namespace fmt {
2672
2673 // adds thousands separator to numbers
2674 NumSep::NumSep(char sep)
2675 : mSep(sep) {}
2676
2677 char NumSep::do_thousands_sep() const {
2678 return mSep;
2679 }
2680
2681 std::string NumSep::do_grouping() const {
2682 return "\003";
2683 }
2684
2685 // RAII to save & restore a stream's state
2686 StreamStateRestorer::StreamStateRestorer(std::ostream& s)
2687 : mStream(s)
2688 , mLocale(s.getloc())
2689 , mPrecision(s.precision())
2690 , mWidth(s.width())
2691 , mFill(s.fill())
2692 , mFmtFlags(s.flags()) {}
2693
2694 StreamStateRestorer::~StreamStateRestorer() {
2695 restore();
2696 }
2697
2698 // sets back all stream info that we remembered at construction
2699 void StreamStateRestorer::restore() {
2700 mStream.imbue(mLocale);
2701 mStream.precision(mPrecision);
2702 mStream.width(mWidth);
2703 mStream.fill(mFill);
2704 mStream.flags(mFmtFlags);
2705 }
2706
2707 Number::Number(int width, int precision, int64_t value)
2708 : mWidth(width)
2709 , mPrecision(precision)
2710 , mValue(static_cast<double>(value)) {}
2711
2712 Number::Number(int width, int precision, double value)
2713 : mWidth(width)
2714 , mPrecision(precision)
2715 , mValue(value) {}
2716
2717 std::ostream& Number::write(std::ostream& os) const {
2718 StreamStateRestorer restorer(os);
2719 os.imbue(std::locale(os.getloc(), new NumSep(',')));
2720 os << std::setw(mWidth) << std::setprecision(mPrecision) << std::fixed << mValue;
2721 return os;
2722 }
2723
2724 std::string Number::to_s() const {
2725 std::stringstream ss;
2726 write(ss);
2727 return ss.str();
2728 }
2729
2730 std::string to_s(uint64_t n) {
2731 std::string str;
2732 do {
2733 str += static_cast<char>('0' + static_cast<char>(n % 10));
2734 n /= 10;
2735 } while (n != 0);
2736 std::reverse(str.begin(), str.end());
2737 return str;
2738 }
2739
2740 std::ostream& operator<<(std::ostream& os, Number const& n) {
2741 return n.write(os);
2742 }
2743
2744 MarkDownColumn::MarkDownColumn(int w, int prec, std::string const& tit, std::string const& suff, double val)
2745 : mWidth(w)
2746 , mPrecision(prec)
2747 , mTitle(tit)
2748 , mSuffix(suff)
2749 , mValue(val) {}
2750
2751 std::string MarkDownColumn::title() const {
2752 std::stringstream ss;
2753 ss << '|' << std::setw(mWidth - 2) << std::right << mTitle << ' ';
2754 return ss.str();
2755 }
2756
2757 std::string MarkDownColumn::separator() const {
2758 std::string sep(static_cast<size_t>(mWidth), '-');
2759 sep.front() = '|';
2760 sep.back() = ':';
2761 return sep;
2762 }
2763
2764 std::string MarkDownColumn::invalid() const {
2765 std::string sep(static_cast<size_t>(mWidth), ' ');
2766 sep.front() = '|';
2767 sep[sep.size() - 2] = '-';
2768 return sep;
2769 }
2770
2771 std::string MarkDownColumn::value() const {
2772 std::stringstream ss;
2773 auto width = mWidth - 2 - static_cast<int>(mSuffix.size());
2774 ss << '|' << Number(width, mPrecision, mValue) << mSuffix << ' ';
2775 return ss.str();
2776 }
2777
2778 // Formats any text as markdown code, escaping backticks.
2779 MarkDownCode::MarkDownCode(std::string const& what) {
2780 mWhat.reserve(what.size() + 2);
2781 mWhat.push_back('`');
2782 for (char c : what) {
2783 mWhat.push_back(c);
2784 if ('`' == c) {
2785 mWhat.push_back('`');
2786 }
2787 }
2788 mWhat.push_back('`');
2789 }
2790
2791 std::ostream& MarkDownCode::write(std::ostream& os) const {
2792 return os << mWhat;
2793 }
2794
2795 std::ostream& operator<<(std::ostream& os, MarkDownCode const& mdCode) {
2796 return mdCode.write(os);
2797 }
2798 } // namespace fmt
2799 } // namespace detail
2800
2801 // provide implementation here so it's only generated once
2802 Config::Config() = default;
2803 Config::~Config() = default;
2804 Config& Config::operator=(Config const&) = default;
2805 Config& Config::operator=(Config&&) = default;
2806 Config::Config(Config const&) = default;
2807 Config::Config(Config&&) noexcept = default;
2808
2809 // provide implementation here so it's only generated once
2810 Result::~Result() = default;
2811 Result& Result::operator=(Result const&) = default;
2812 Result& Result::operator=(Result&&) = default;
2813 Result::Result(Result const&) = default;
2814 Result::Result(Result&&) noexcept = default;
2815
2816 namespace detail {
2817 template <typename T>
2818 inline constexpr typename std::underlying_type<T>::type u(T val) noexcept {
2819 return static_cast<typename std::underlying_type<T>::type>(val);
2820 }
2821 } // namespace detail
2822
2823 // Result returned after a benchmark has finished. Can be used as a baseline for relative().
2824 Result::Result(Config const& benchmarkConfig)
2825 : mConfig(benchmarkConfig)
2826 , mNameToMeasurements{detail::u(Result::Measure::_size)} {}
2827
2828 void Result::add(Clock::duration totalElapsed, uint64_t iters, detail::PerformanceCounters const& pc) {
2829 using detail::d;
2830 using detail::u;
2831
2832 double dIters = d(iters);
2833 mNameToMeasurements[u(Result::Measure::iterations)].push_back(dIters);
2834
2835 mNameToMeasurements[u(Result::Measure::elapsed)].push_back(d(totalElapsed) / dIters);
2836 if (pc.has().pageFaults) {
2837 mNameToMeasurements[u(Result::Measure::pagefaults)].push_back(d(pc.val().pageFaults) / dIters);
2838 }
2839 if (pc.has().cpuCycles) {
2840 mNameToMeasurements[u(Result::Measure::cpucycles)].push_back(d(pc.val().cpuCycles) / dIters);
2841 }
2842 if (pc.has().contextSwitches) {
2843 mNameToMeasurements[u(Result::Measure::contextswitches)].push_back(d(pc.val().contextSwitches) / dIters);
2844 }
2845 if (pc.has().instructions) {
2846 mNameToMeasurements[u(Result::Measure::instructions)].push_back(d(pc.val().instructions) / dIters);
2847 }
2848 if (pc.has().branchInstructions) {
2849 double branchInstructions = 0.0;
2850 // correcting branches: remove branch introduced by the while (...) loop for each iteration.
2851 if (pc.val().branchInstructions > iters + 1U) {
2852 branchInstructions = d(pc.val().branchInstructions - (iters + 1U));
2853 }
2854 mNameToMeasurements[u(Result::Measure::branchinstructions)].push_back(branchInstructions / dIters);
2855
2856 if (pc.has().branchMisses) {
2857 // correcting branch misses
2858 double branchMisses = d(pc.val().branchMisses);
2859 if (branchMisses > branchInstructions) {
2860 // can't have branch misses when there were branches...
2861 branchMisses = branchInstructions;
2862 }
2863
2864 // assuming at least one missed branch for the loop
2865 branchMisses -= 1.0;
2866 if (branchMisses < 1.0) {
2867 branchMisses = 1.0;
2868 }
2869 mNameToMeasurements[u(Result::Measure::branchmisses)].push_back(branchMisses / dIters);
2870 }
2871 }
2872 }
2873
2874 Config const& Result::config() const noexcept {
2875 return mConfig;
2876 }
2877
2878 inline double calcMedian(std::vector<double>& data) {
2879 if (data.empty()) {
2880 return 0.0;
2881 }
2882 std::sort(data.begin(), data.end());
2883
2884 auto midIdx = data.size() / 2U;
2885 if (1U == (data.size() & 1U)) {
2886 return data[midIdx];
2887 }
2888 return (data[midIdx - 1U] + data[midIdx]) / 2U;
2889 }
2890
2891 double Result::median(Measure m) const {
2892 // create a copy so we can sort
2893 auto data = mNameToMeasurements[detail::u(m)];
2894 return calcMedian(data);
2895 }
2896
2897 double Result::average(Measure m) const {
2898 using detail::d;
2899 auto const& data = mNameToMeasurements[detail::u(m)];
2900 if (data.empty()) {
2901 return 0.0;
2902 }
2903
2904 // create a copy so we can sort
2905 return sum(m) / d(data.size());
2906 }
2907
2908 double Result::medianAbsolutePercentError(Measure m) const {
2909 // create copy
2910 auto data = mNameToMeasurements[detail::u(m)];
2911
2912 // calculates MdAPE which is the median of percentage error
2913 // see https://www.spiderfinancial.com/support/documentation/numxl/reference-manual/forecasting-performance/mdape
2914 auto med = calcMedian(data);
2915
2916 // transform the data to absolute error
2917 for (auto& x : data) {
2918 x = (x - med) / x;
2919 if (x < 0) {
2920 x = -x;
2921 }
2922 }
2923 return calcMedian(data);
2924 }
2925
2926 double Result::sum(Measure m) const noexcept {
2927 auto const& data = mNameToMeasurements[detail::u(m)];
2928 return std::accumulate(data.begin(), data.end(), 0.0);
2929 }
2930
2931 double Result::sumProduct(Measure m1, Measure m2) const noexcept {
2932 auto const& data1 = mNameToMeasurements[detail::u(m1)];
2933 auto const& data2 = mNameToMeasurements[detail::u(m2)];
2934
2935 if (data1.size() != data2.size()) {
2936 return 0.0;
2937 }
2938
2939 double result = 0.0;
2940 for (size_t i = 0, s = data1.size(); i != s; ++i) {
2941 result += data1[i] * data2[i];
2942 }
2943 return result;
2944 }
2945
2946 bool Result::has(Measure m) const noexcept {
2947 return !mNameToMeasurements[detail::u(m)].empty();
2948 }
2949
2950 double Result::get(size_t idx, Measure m) const {
2951 auto const& data = mNameToMeasurements[detail::u(m)];
2952 return data.at(idx);
2953 }
2954
2955 bool Result::empty() const noexcept {
2956 return 0U == size();
2957 }
2958
2959 size_t Result::size() const noexcept {
2960 auto const& data = mNameToMeasurements[detail::u(Measure::elapsed)];
2961 return data.size();
2962 }
2963
2964 double Result::minimum(Measure m) const noexcept {
2965 auto const& data = mNameToMeasurements[detail::u(m)];
2966 if (data.empty()) {
2967 return 0.0;
2968 }
2969
2970 // here its save to assume that at least one element is there
2971 return *std::min_element(data.begin(), data.end());
2972 }
2973
2974 double Result::maximum(Measure m) const noexcept {
2975 auto const& data = mNameToMeasurements[detail::u(m)];
2976 if (data.empty()) {
2977 return 0.0;
2978 }
2979
2980 // here its save to assume that at least one element is there
2981 return *std::max_element(data.begin(), data.end());
2982 }
2983
2984 Result::Measure Result::fromString(std::string const& str) {
2985 if (str == "elapsed") {
2986 return Measure::elapsed;
2987 } else if (str == "iterations") {
2988 return Measure::iterations;
2989 } else if (str == "pagefaults") {
2990 return Measure::pagefaults;
2991 } else if (str == "cpucycles") {
2992 return Measure::cpucycles;
2993 } else if (str == "contextswitches") {
2994 return Measure::contextswitches;
2995 } else if (str == "instructions") {
2996 return Measure::instructions;
2997 } else if (str == "branchinstructions") {
2998 return Measure::branchinstructions;
2999 } else if (str == "branchmisses") {
3000 return Measure::branchmisses;
3001 } else {
3002 // not found, return _size
3003 return Measure::_size;
3004 }
3005 }
3006
3007 // Configuration of a microbenchmark.
3008 Bench::Bench() {
3009 mConfig.mOut = &std::cout;
3010 }
3011
3012 Bench::Bench(Bench&&) = default;
3013 Bench& Bench::operator=(Bench&&) = default;
3014 Bench::Bench(Bench const&) = default;
3015 Bench& Bench::operator=(Bench const&) = default;
3016 Bench::~Bench() noexcept = default;
3017
3018 double Bench::batch() const noexcept {
3019 return mConfig.mBatch;
3020 }
3021
3022 double Bench::complexityN() const noexcept {
3023 return mConfig.mComplexityN;
3024 }
3025
3026 // Set a baseline to compare it to. 100% it is exactly as fast as the baseline, >100% means it is faster than the baseline, <100%
3027 // means it is slower than the baseline.
3028 Bench& Bench::relative(bool isRelativeEnabled) noexcept {
3029 mConfig.mIsRelative = isRelativeEnabled;
3030 return *this;
3031 }
3032 bool Bench::relative() const noexcept {
3033 return mConfig.mIsRelative;
3034 }
3035
3036 Bench& Bench::performanceCounters(bool showPerformanceCounters) noexcept {
3037 mConfig.mShowPerformanceCounters = showPerformanceCounters;
3038 return *this;
3039 }
3040 bool Bench::performanceCounters() const noexcept {
3041 return mConfig.mShowPerformanceCounters;
3042 }
3043
3044 // Operation unit. Defaults to "op", could be e.g. "byte" for string processing.
3045 // If u differs from currently set unit, the stored results will be cleared.
3046 // Use singular (byte, not bytes).
3047 Bench& Bench::unit(char const* u) {
3048 if (u != mConfig.mUnit) {
3049 mResults.clear();
3050 }
3051 mConfig.mUnit = u;
3052 return *this;
3053 }
3054
3055 Bench& Bench::unit(std::string const& u) {
3056 return unit(u.c_str());
3057 }
3058
3059 std::string const& Bench::unit() const noexcept {
3060 return mConfig.mUnit;
3061 }
3062
3063 Bench& Bench::timeUnit(std::chrono::duration<double> const& tu, std::string const& tuName) {
3064 mConfig.mTimeUnit = tu;
3065 mConfig.mTimeUnitName = tuName;
3066 return *this;
3067 }
3068
3069 std::string const& Bench::timeUnitName() const noexcept {
3070 return mConfig.mTimeUnitName;
3071 }
3072
3073 std::chrono::duration<double> const& Bench::timeUnit() const noexcept {
3074 return mConfig.mTimeUnit;
3075 }
3076
3077 // If benchmarkTitle differs from currently set title, the stored results will be cleared.
3078 Bench& Bench::title(const char* benchmarkTitle) {
3079 if (benchmarkTitle != mConfig.mBenchmarkTitle) {
3080 mResults.clear();
3081 }
3082 mConfig.mBenchmarkTitle = benchmarkTitle;
3083 return *this;
3084 }
3085 Bench& Bench::title(std::string const& benchmarkTitle) {
3086 if (benchmarkTitle != mConfig.mBenchmarkTitle) {
3087 mResults.clear();
3088 }
3089 mConfig.mBenchmarkTitle = benchmarkTitle;
3090 return *this;
3091 }
3092
3093 std::string const& Bench::title() const noexcept {
3094 return mConfig.mBenchmarkTitle;
3095 }
3096
3097 Bench& Bench::name(const char* benchmarkName) {
3098 mConfig.mBenchmarkName = benchmarkName;
3099 return *this;
3100 }
3101
3102 Bench& Bench::name(std::string const& benchmarkName) {
3103 mConfig.mBenchmarkName = benchmarkName;
3104 return *this;
3105 }
3106
3107 std::string const& Bench::name() const noexcept {
3108 return mConfig.mBenchmarkName;
3109 }
3110
3111 // Number of epochs to evaluate. The reported result will be the median of evaluation of each epoch.
3112 Bench& Bench::epochs(size_t numEpochs) noexcept {
3113 mConfig.mNumEpochs = numEpochs;
3114 return *this;
3115 }
3116 size_t Bench::epochs() const noexcept {
3117 return mConfig.mNumEpochs;
3118 }
3119
3120 // Desired evaluation time is a multiple of clock resolution. Default is to be 1000 times above this measurement precision.
3121 Bench& Bench::clockResolutionMultiple(size_t multiple) noexcept {
3122 mConfig.mClockResolutionMultiple = multiple;
3123 return *this;
3124 }
3125 size_t Bench::clockResolutionMultiple() const noexcept {
3126 return mConfig.mClockResolutionMultiple;
3127 }
3128
3129 // Sets the maximum time each epoch should take. Default is 100ms.
3130 Bench& Bench::maxEpochTime(std::chrono::nanoseconds t) noexcept {
3131 mConfig.mMaxEpochTime = t;
3132 return *this;
3133 }
3134 std::chrono::nanoseconds Bench::maxEpochTime() const noexcept {
3135 return mConfig.mMaxEpochTime;
3136 }
3137
3138 // Sets the maximum time each epoch should take. Default is 100ms.
3139 Bench& Bench::minEpochTime(std::chrono::nanoseconds t) noexcept {
3140 mConfig.mMinEpochTime = t;
3141 return *this;
3142 }
3143 std::chrono::nanoseconds Bench::minEpochTime() const noexcept {
3144 return mConfig.mMinEpochTime;
3145 }
3146
3147 Bench& Bench::minEpochIterations(uint64_t numIters) noexcept {
3148 mConfig.mMinEpochIterations = (numIters == 0) ? 1 : numIters;
3149 return *this;
3150 }
3151 uint64_t Bench::minEpochIterations() const noexcept {
3152 return mConfig.mMinEpochIterations;
3153 }
3154
3155 Bench& Bench::epochIterations(uint64_t numIters) noexcept {
3156 mConfig.mEpochIterations = numIters;
3157 return *this;
3158 }
3159 uint64_t Bench::epochIterations() const noexcept {
3160 return mConfig.mEpochIterations;
3161 }
3162
3163 Bench& Bench::warmup(uint64_t numWarmupIters) noexcept {
3164 mConfig.mWarmup = numWarmupIters;
3165 return *this;
3166 }
3167 uint64_t Bench::warmup() const noexcept {
3168 return mConfig.mWarmup;
3169 }
3170
3171 Bench& Bench::config(Config const& benchmarkConfig) {
3172 mConfig = benchmarkConfig;
3173 return *this;
3174 }
3175 Config const& Bench::config() const noexcept {
3176 return mConfig;
3177 }
3178
3179 Bench& Bench::output(std::ostream* outstream) noexcept {
3180 mConfig.mOut = outstream;
3181 return *this;
3182 }
3183
3184 ANKERL_NANOBENCH(NODISCARD) std::ostream* Bench::output() const noexcept {
3185 return mConfig.mOut;
3186 }
3187
3188 std::vector<Result> const& Bench::results() const noexcept {
3189 return mResults;
3190 }
3191
3192 Bench& Bench::render(char const* templateContent, std::ostream& os) {
3193 ::ankerl::nanobench::render(templateContent, *this, os);
3194 return *this;
3195 }
3196
3197 Bench& Bench::render(std::string const& templateContent, std::ostream& os) {
3198 ::ankerl::nanobench::render(templateContent, *this, os);
3199 return *this;
3200 }
3201
3202 std::vector<BigO> Bench::complexityBigO() const {
3203 std::vector<BigO> bigOs;
3204 auto rangeMeasure = BigO::collectRangeMeasure(mResults);
3205 bigOs.emplace_back("O(1)", rangeMeasure, [](double) {
3206 return 1.0;
3207 });
3208 bigOs.emplace_back("O(n)", rangeMeasure, [](double n) {
3209 return n;
3210 });
3211 bigOs.emplace_back("O(log n)", rangeMeasure, [](double n) {
3212 return std::log2(n);
3213 });
3214 bigOs.emplace_back("O(n log n)", rangeMeasure, [](double n) {
3215 return n * std::log2(n);
3216 });
3217 bigOs.emplace_back("O(n^2)", rangeMeasure, [](double n) {
3218 return n * n;
3219 });
3220 bigOs.emplace_back("O(n^3)", rangeMeasure, [](double n) {
3221 return n * n * n;
3222 });
3223 std::sort(bigOs.begin(), bigOs.end());
3224 return bigOs;
3225 }
3226
3227 Rng::Rng()
3228 : mX(0)
3229 , mY(0) {
3230 std::random_device rd;
3231 std::uniform_int_distribution<uint64_t> dist;
3232 do {
3233 mX = dist(rd);
3234 mY = dist(rd);
3235 } while (mX == 0 && mY == 0);
3236 }
3237
3238 ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined")
3239 uint64_t splitMix64(uint64_t& state) noexcept {
3240 uint64_t z = (state += UINT64_C(0x9e3779b97f4a7c15));
3241 z = (z ^ (z >> 30U)) * UINT64_C(0xbf58476d1ce4e5b9);
3242 z = (z ^ (z >> 27U)) * UINT64_C(0x94d049bb133111eb);
3243 return z ^ (z >> 31U);
3244 }
3245
3246 // Seeded as described in romu paper (update april 2020)
3247 Rng::Rng(uint64_t seed) noexcept
3248 : mX(splitMix64(seed))
3249 , mY(splitMix64(seed)) {
3250 for (size_t i = 0; i < 10; ++i) {
3251 operator()();
3252 }
3253 }
3254
3255 // only internally used to copy the RNG.
3256 Rng::Rng(uint64_t x, uint64_t y) noexcept
3257 : mX(x)
3258 , mY(y) {}
3259
3260 Rng Rng::copy() const noexcept {
3261 return Rng{mX, mY};
3262 }
3263
3264 Rng::Rng(std::vector<uint64_t> const& data)
3265 : mX(0)
3266 , mY(0) {
3267 if (data.size() != 2) {
3268 throw std::runtime_error("ankerl::nanobench::Rng::Rng: needed exactly 2 entries in data, but got " +
3269 std::to_string(data.size()));
3270 }
3271 mX = data[0];
3272 mY = data[1];
3273 }
3274
3275 std::vector<uint64_t> Rng::state() const {
3276 std::vector<uint64_t> data(2);
3277 data[0] = mX;
3278 data[1] = mY;
3279 return data;
3280 }
3281
3282 BigO::RangeMeasure BigO::collectRangeMeasure(std::vector<Result> const& results) {
3283 BigO::RangeMeasure rangeMeasure;
3284 for (auto const& result : results) {
3285 if (result.config().mComplexityN > 0.0) {
3286 rangeMeasure.emplace_back(result.config().mComplexityN, result.median(Result::Measure::elapsed));
3287 }
3288 }
3289 return rangeMeasure;
3290 }
3291
3292 BigO::BigO(std::string const& bigOName, RangeMeasure const& rangeMeasure)
3293 : mName(bigOName) {
3294
3295 // estimate the constant factor
3296 double sumRangeMeasure = 0.0;
3297 double sumRangeRange = 0.0;
3298
3299 for (size_t i = 0; i < rangeMeasure.size(); ++i) {
3300 sumRangeMeasure += rangeMeasure[i].first * rangeMeasure[i].second;
3301 sumRangeRange += rangeMeasure[i].first * rangeMeasure[i].first;
3302 }
3303 mConstant = sumRangeMeasure / sumRangeRange;
3304
3305 // calculate root mean square
3306 double err = 0.0;
3307 double sumMeasure = 0.0;
3308 for (size_t i = 0; i < rangeMeasure.size(); ++i) {
3309 auto diff = mConstant * rangeMeasure[i].first - rangeMeasure[i].second;
3310 err += diff * diff;
3311
3312 sumMeasure += rangeMeasure[i].second;
3313 }
3314
3315 auto n = static_cast<double>(rangeMeasure.size());
3316 auto mean = sumMeasure / n;
3317 mNormalizedRootMeanSquare = std::sqrt(err / n) / mean;
3318 }
3319
3320 BigO::BigO(const char* bigOName, RangeMeasure const& rangeMeasure)
3321 : BigO(std::string(bigOName), rangeMeasure) {}
3322
3323 std::string const& BigO::name() const noexcept {
3324 return mName;
3325 }
3326
3327 double BigO::constant() const noexcept {
3328 return mConstant;
3329 }
3330
3331 double BigO::normalizedRootMeanSquare() const noexcept {
3332 return mNormalizedRootMeanSquare;
3333 }
3334
3335 bool BigO::operator<(BigO const& other) const noexcept {
3336 return std::tie(mNormalizedRootMeanSquare, mName) < std::tie(other.mNormalizedRootMeanSquare, other.mName);
3337 }
3338
3339 std::ostream& operator<<(std::ostream& os, BigO const& bigO) {
3340 return os << bigO.constant() << " * " << bigO.name() << ", rms=" << bigO.normalizedRootMeanSquare();
3341 }
3342
3343 std::ostream& operator<<(std::ostream& os, std::vector<ankerl::nanobench::BigO> const& bigOs) {
3344 detail::fmt::StreamStateRestorer restorer(os);
3345 os << std::endl << "| coefficient | err% | complexity" << std::endl << "|--------------:|-------:|------------" << std::endl;
3346 for (auto const& bigO : bigOs) {
3347 os << "|" << std::setw(14) << std::setprecision(7) << std::scientific << bigO.constant() << " ";
3348 os << "|" << detail::fmt::Number(6, 1, bigO.normalizedRootMeanSquare() * 100.0) << "% ";
3349 os << "| " << bigO.name();
3350 os << std::endl;
3351 }
3352 return os;
3353 }
3354
3355 } // namespace nanobench
3356 } // namespace ankerl
3357
3358 #endif // ANKERL_NANOBENCH_IMPLEMENT
3359 #endif // ANKERL_NANOBENCH_H_INCLUDED