Bitcoin Core  0.21.1
P2P Digital Currency
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
nanobench.h
Go to the documentation of this file.
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-2020 Martin Ankerl <martin.ankerl@gmail.com>
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 0 // backwards-compatible changes
36 #define ANKERL_NANOBENCH_VERSION_PATCH 0 // backwards-compatible bug fixes
37 
39 // public facing api - as minimal as possible
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) std::cout << __FUNCTION__ << "@" << __LINE__ << ": " << x << std::endl
82 #else
83 # define ANKERL_NANOBENCH_LOG(x)
84 #endif
85 
86 #if defined(__linux__) && !defined(ANKERL_NANOBENCH_DISABLE_PERF_COUNTERS)
87 # define ANKERL_NANOBENCH_PRIVATE_PERF_COUNTERS() 1
88 #else
89 # define ANKERL_NANOBENCH_PRIVATE_PERF_COUNTERS() 0
90 #endif
91 
92 #if defined(__clang__)
93 # define ANKERL_NANOBENCH_NO_SANITIZE(...) __attribute__((no_sanitize(__VA_ARGS__)))
94 #else
95 # define ANKERL_NANOBENCH_NO_SANITIZE(...)
96 #endif
97 
98 #if defined(_MSC_VER)
99 # define ANKERL_NANOBENCH_PRIVATE_NOINLINE() __declspec(noinline)
100 #else
101 # define ANKERL_NANOBENCH_PRIVATE_NOINLINE() __attribute__((noinline))
102 #endif
103 
104 // workaround missing "is_trivially_copyable" in g++ < 5.0
105 // See https://stackoverflow.com/a/31798726/48181
106 #if defined(__GNUC__) && __GNUC__ < 5
107 # define ANKERL_NANOBENCH_IS_TRIVIALLY_COPYABLE(...) __has_trivial_copy(__VA_ARGS__)
108 #else
109 # define ANKERL_NANOBENCH_IS_TRIVIALLY_COPYABLE(...) std::is_trivially_copyable<__VA_ARGS__>::value
110 #endif
111 
112 // declarations ///////////////////////////////////////////////////////////////////////////////////
113 
114 namespace ankerl {
115 namespace nanobench {
116 
117 using Clock = std::conditional<std::chrono::high_resolution_clock::is_steady, std::chrono::high_resolution_clock,
118  std::chrono::steady_clock>::type;
119 class Bench;
120 struct Config;
121 class Result;
122 class Rng;
123 class BigO;
124 
271 void render(char const* mustacheTemplate, Bench const& bench, std::ostream& out);
272 
281 void render(char const* mustacheTemplate, std::vector<Result> const& results, std::ostream& out);
282 
283 // Contains mustache-like templates
284 namespace templates {
285 
295 char const* csv() noexcept;
296 
307 char const* htmlBoxplot() noexcept;
308 
318 char const* json() noexcept;
319 
320 } // namespace templates
321 
322 namespace detail {
323 
324 template <typename T>
326 
327 class IterationLogic;
328 class PerformanceCounters;
329 
330 #if ANKERL_NANOBENCH(PERF_COUNTERS)
331 class LinuxPerformanceCounters;
332 #endif
333 
334 } // namespace detail
335 } // namespace nanobench
336 } // namespace ankerl
337 
338 // definitions ////////////////////////////////////////////////////////////////////////////////////
339 
340 namespace ankerl {
341 namespace nanobench {
342 namespace detail {
343 
344 template <typename T>
345 struct PerfCountSet {
352 };
353 
354 } // namespace detail
355 
356 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
357 struct Config {
358  // actual benchmark config
359  std::string mBenchmarkTitle = "benchmark";
360  std::string mBenchmarkName = "noname";
361  std::string mUnit = "op";
362  double mBatch = 1.0;
363  double mComplexityN = -1.0;
364  size_t mNumEpochs = 11;
365  size_t mClockResolutionMultiple = static_cast<size_t>(1000);
366  std::chrono::nanoseconds mMaxEpochTime = std::chrono::milliseconds(100);
367  std::chrono::nanoseconds mMinEpochTime{};
368  uint64_t mMinEpochIterations{1};
369  uint64_t mEpochIterations{0}; // If not 0, run *exactly* these number of iterations per epoch.
370  uint64_t mWarmup = 0;
371  std::ostream* mOut = nullptr;
372  bool mShowPerformanceCounters = true;
373  bool mIsRelative = false;
374 
375  Config();
376  ~Config();
377  Config& operator=(Config const&);
378  Config& operator=(Config&&);
379  Config(Config const&);
380  Config(Config&&) noexcept;
381 };
382 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
383 
384 // Result returned after a benchmark has finished. Can be used as a baseline for relative().
385 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
386 class Result {
387 public:
388  enum class Measure : size_t {
389  elapsed,
390  iterations,
391  pagefaults,
392  cpucycles,
393  contextswitches,
394  instructions,
395  branchinstructions,
396  branchmisses,
397  _size
398  };
399 
400  explicit Result(Config const& benchmarkConfig);
401 
402  ~Result();
403  Result& operator=(Result const&);
404  Result& operator=(Result&&);
405  Result(Result const&);
406  Result(Result&&) noexcept;
407 
408  // adds new measurement results
409  // all values are scaled by iters (except iters...)
410  void add(Clock::duration totalElapsed, uint64_t iters, detail::PerformanceCounters const& pc);
411 
412  ANKERL_NANOBENCH(NODISCARD) Config const& config() const noexcept;
413 
414  ANKERL_NANOBENCH(NODISCARD) double median(Measure m) const;
415  ANKERL_NANOBENCH(NODISCARD) double medianAbsolutePercentError(Measure m) const;
416  ANKERL_NANOBENCH(NODISCARD) double average(Measure m) const;
417  ANKERL_NANOBENCH(NODISCARD) double sum(Measure m) const noexcept;
418  ANKERL_NANOBENCH(NODISCARD) double sumProduct(Measure m1, Measure m2) const noexcept;
419  ANKERL_NANOBENCH(NODISCARD) double minimum(Measure m) const noexcept;
420  ANKERL_NANOBENCH(NODISCARD) double maximum(Measure m) const noexcept;
421 
422  ANKERL_NANOBENCH(NODISCARD) bool has(Measure m) const noexcept;
423  ANKERL_NANOBENCH(NODISCARD) double get(size_t idx, Measure m) const;
424  ANKERL_NANOBENCH(NODISCARD) bool empty() const noexcept;
425  ANKERL_NANOBENCH(NODISCARD) size_t size() const noexcept;
426 
427  // Finds string, if not found, returns _size.
428  static Measure fromString(std::string const& str);
429 
430 private:
431  Config mConfig{};
432  std::vector<std::vector<double>> mNameToMeasurements{};
433 };
434 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
435 
436 
453 class Rng final {
454 public:
458  using result_type = uint64_t;
459 
460  static constexpr uint64_t(min)();
461  static constexpr uint64_t(max)();
462 
468  Rng(Rng const&) = delete;
469 
473  Rng& operator=(Rng const&) = delete;
474 
475  // moving is ok
476  Rng(Rng&&) noexcept = default;
477  Rng& operator=(Rng&&) noexcept = default;
478  ~Rng() noexcept = default;
479 
487  Rng();
488 
505  explicit Rng(uint64_t seed) noexcept;
506  Rng(uint64_t x, uint64_t y) noexcept;
507 
511  ANKERL_NANOBENCH(NODISCARD) Rng copy() const noexcept;
512 
520  inline uint64_t operator()() noexcept;
521 
522  // This is slightly biased. See
523 
538  inline uint32_t bounded(uint32_t range) noexcept;
539 
540  // random double in range [0, 1(
541  // see http://prng.di.unimi.it/
542 
549  inline double uniform01() noexcept;
550 
558  template <typename Container>
559  void shuffle(Container& container) noexcept;
560 
561 private:
562  static constexpr uint64_t rotl(uint64_t x, unsigned k) noexcept;
563 
564  uint64_t mX;
565  uint64_t mY;
566 };
567 
582 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
583 class Bench {
584 public:
588  Bench();
589 
590  Bench(Bench&& other);
591  Bench& operator=(Bench&& other);
592  Bench(Bench const& other);
593  Bench& operator=(Bench const& other);
594  ~Bench() noexcept;
595 
614  template <typename Op>
615  ANKERL_NANOBENCH(NOINLINE)
616  Bench& run(char const* benchmarkName, Op&& op);
617 
618  template <typename Op>
619  ANKERL_NANOBENCH(NOINLINE)
620  Bench& run(std::string const& benchmarkName, Op&& op);
621 
626  template <typename Op>
627  ANKERL_NANOBENCH(NOINLINE)
628  Bench& run(Op&& op);
629 
635  Bench& title(char const* benchmarkTitle);
636  Bench& title(std::string const& benchmarkTitle);
637  ANKERL_NANOBENCH(NODISCARD) std::string const& title() const noexcept;
638 
640  Bench& name(char const* benchmarkName);
641  Bench& name(std::string const& benchmarkName);
642  ANKERL_NANOBENCH(NODISCARD) std::string const& name() const noexcept;
643 
653  template <typename T>
654  Bench& batch(T b) noexcept;
655  ANKERL_NANOBENCH(NODISCARD) double batch() const noexcept;
656 
665  Bench& unit(char const* unit);
666  Bench& unit(std::string const& unit);
667  ANKERL_NANOBENCH(NODISCARD) std::string const& unit() const noexcept;
668 
676  Bench& output(std::ostream* outstream) noexcept;
677  ANKERL_NANOBENCH(NODISCARD) std::ostream* output() const noexcept;
678 
699  Bench& clockResolutionMultiple(size_t multiple) noexcept;
700  ANKERL_NANOBENCH(NODISCARD) size_t clockResolutionMultiple() const noexcept;
701 
717  Bench& epochs(size_t numEpochs) noexcept;
718  ANKERL_NANOBENCH(NODISCARD) size_t epochs() const noexcept;
719 
730  Bench& maxEpochTime(std::chrono::nanoseconds t) noexcept;
731  ANKERL_NANOBENCH(NODISCARD) std::chrono::nanoseconds maxEpochTime() const noexcept;
732 
743  Bench& minEpochTime(std::chrono::nanoseconds t) noexcept;
744  ANKERL_NANOBENCH(NODISCARD) std::chrono::nanoseconds minEpochTime() const noexcept;
745 
756  Bench& minEpochIterations(uint64_t numIters) noexcept;
757  ANKERL_NANOBENCH(NODISCARD) uint64_t minEpochIterations() const noexcept;
758 
765  Bench& epochIterations(uint64_t numIters) noexcept;
766  ANKERL_NANOBENCH(NODISCARD) uint64_t epochIterations() const noexcept;
767 
777  Bench& warmup(uint64_t numWarmupIters) noexcept;
778  ANKERL_NANOBENCH(NODISCARD) uint64_t warmup() const noexcept;
779 
797  Bench& relative(bool isRelativeEnabled) noexcept;
798  ANKERL_NANOBENCH(NODISCARD) bool relative() const noexcept;
799 
808  Bench& performanceCounters(bool showPerformanceCounters) noexcept;
809  ANKERL_NANOBENCH(NODISCARD) bool performanceCounters() const noexcept;
810 
819  ANKERL_NANOBENCH(NODISCARD) std::vector<Result> const& results() const noexcept;
820 
828  template <typename Arg>
829  Bench& doNotOptimizeAway(Arg&& arg);
830 
845  template <typename T>
846  Bench& complexityN(T b) noexcept;
847  ANKERL_NANOBENCH(NODISCARD) double complexityN() const noexcept;
848 
880  std::vector<BigO> complexityBigO() const;
881 
905  template <typename Op>
906  BigO complexityBigO(char const* name, Op op) const;
907 
908  template <typename Op>
909  BigO complexityBigO(std::string const& name, Op op) const;
910 
918  Bench& render(char const* templateContent, std::ostream& os);
919 
920  Bench& config(Config const& benchmarkConfig);
921  ANKERL_NANOBENCH(NODISCARD) Config const& config() const noexcept;
922 
923 private:
924  Config mConfig{};
925  std::vector<Result> mResults{};
926 };
927 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
928 
929 
935 template <typename Arg>
936 void doNotOptimizeAway(Arg&& arg);
937 
938 namespace detail {
939 
940 #if defined(_MSC_VER)
941 void doNotOptimizeAwaySink(void const*);
942 
943 template <typename T>
944 void doNotOptimizeAway(T const& val);
945 
946 #else
947 
948 // see folly's Benchmark.h
949 template <typename T>
950 constexpr bool doNotOptimizeNeedsIndirect() {
951  using Decayed = typename std::decay<T>::type;
952  return !ANKERL_NANOBENCH_IS_TRIVIALLY_COPYABLE(Decayed) || sizeof(Decayed) > sizeof(long) || std::is_pointer<Decayed>::value;
953 }
954 
955 template <typename T>
956 typename std::enable_if<!doNotOptimizeNeedsIndirect<T>()>::type doNotOptimizeAway(T const& val) {
957  // NOLINTNEXTLINE(hicpp-no-assembler)
958  asm volatile("" ::"r"(val));
959 }
960 
961 template <typename T>
962 typename std::enable_if<doNotOptimizeNeedsIndirect<T>()>::type doNotOptimizeAway(T const& val) {
963  // NOLINTNEXTLINE(hicpp-no-assembler)
964  asm volatile("" ::"m"(val) : "memory");
965 }
966 #endif
967 
968 // internally used, but visible because run() is templated.
969 // Not movable/copy-able, so we simply use a pointer instead of unique_ptr. This saves us from
970 // having to include <memory>, and the template instantiation overhead of unique_ptr which is unfortunately quite significant.
971 ANKERL_NANOBENCH(IGNORE_EFFCPP_PUSH)
973 public:
974  explicit IterationLogic(Bench const& config) noexcept;
975  ~IterationLogic();
976 
977  ANKERL_NANOBENCH(NODISCARD) uint64_t numIters() const noexcept;
978  void add(std::chrono::nanoseconds elapsed, PerformanceCounters const& pc) noexcept;
979  void moveResultTo(std::vector<Result>& results) noexcept;
980 
981 private:
982  struct Impl;
983  Impl* mPimpl;
984 };
985 ANKERL_NANOBENCH(IGNORE_EFFCPP_POP)
986 
987 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
989 public:
990  PerformanceCounters(PerformanceCounters const&) = delete;
991  PerformanceCounters& operator=(PerformanceCounters const&) = delete;
992 
993  PerformanceCounters();
994  ~PerformanceCounters();
995 
996  void beginMeasure();
997  void endMeasure();
998  void updateResults(uint64_t numIters);
999 
1000  ANKERL_NANOBENCH(NODISCARD) PerfCountSet<uint64_t> const& val() const noexcept;
1001  ANKERL_NANOBENCH(NODISCARD) PerfCountSet<bool> const& has() const noexcept;
1002 
1003 private:
1004 #if ANKERL_NANOBENCH(PERF_COUNTERS)
1005  LinuxPerformanceCounters* mPc = nullptr;
1006 #endif
1009 };
1010 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
1011 
1012 // Gets the singleton
1013 PerformanceCounters& performanceCounters();
1014 
1015 } // namespace detail
1016 
1017 class BigO {
1018 public:
1019  using RangeMeasure = std::vector<std::pair<double, double>>;
1020 
1021  template <typename Op>
1023  for (auto& rangeMeasure : data) {
1024  rangeMeasure.first = op(rangeMeasure.first);
1025  }
1026  return data;
1027  }
1028 
1029  static RangeMeasure collectRangeMeasure(std::vector<Result> const& results);
1030 
1031  template <typename Op>
1032  BigO(char const* bigOName, RangeMeasure const& rangeMeasure, Op rangeToN)
1033  : BigO(bigOName, mapRangeMeasure(rangeMeasure, rangeToN)) {}
1034 
1035  template <typename Op>
1036  BigO(std::string const& bigOName, RangeMeasure const& rangeMeasure, Op rangeToN)
1037  : BigO(bigOName, mapRangeMeasure(rangeMeasure, rangeToN)) {}
1038 
1039  BigO(char const* bigOName, RangeMeasure const& scaledRangeMeasure);
1040  BigO(std::string const& bigOName, RangeMeasure const& scaledRangeMeasure);
1041  ANKERL_NANOBENCH(NODISCARD) std::string const& name() const noexcept;
1042  ANKERL_NANOBENCH(NODISCARD) double constant() const noexcept;
1043  ANKERL_NANOBENCH(NODISCARD) double normalizedRootMeanSquare() const noexcept;
1044  ANKERL_NANOBENCH(NODISCARD) bool operator<(BigO const& other) const noexcept;
1045 
1046 private:
1047  std::string mName{};
1048  double mConstant{};
1049  double mNormalizedRootMeanSquare{};
1050 };
1051 std::ostream& operator<<(std::ostream& os, BigO const& bigO);
1052 std::ostream& operator<<(std::ostream& os, std::vector<ankerl::nanobench::BigO> const& bigOs);
1053 
1054 } // namespace nanobench
1055 } // namespace ankerl
1056 
1057 // implementation /////////////////////////////////////////////////////////////////////////////////
1058 
1059 namespace ankerl {
1060 namespace nanobench {
1061 
1062 constexpr uint64_t(Rng::min)() {
1063  return 0;
1064 }
1065 
1066 constexpr uint64_t(Rng::max)() {
1067  return (std::numeric_limits<uint64_t>::max)();
1068 }
1069 
1071 uint64_t Rng::operator()() noexcept {
1072  auto x = mX;
1073 
1074  mX = UINT64_C(15241094284759029579) * mY;
1075  mY = rotl(mY - x, 27);
1076 
1077  return x;
1078 }
1079 
1081 uint32_t Rng::bounded(uint32_t range) noexcept {
1082  uint64_t r32 = static_cast<uint32_t>(operator()());
1083  auto multiresult = r32 * range;
1084  return static_cast<uint32_t>(multiresult >> 32U);
1085 }
1086 
1087 double Rng::uniform01() noexcept {
1088  auto i = (UINT64_C(0x3ff) << 52U) | (operator()() >> 12U);
1089  // can't use union in c++ here for type puning, it's undefined behavior.
1090  // std::memcpy is optimized anyways.
1091  double d;
1092  std::memcpy(&d, &i, sizeof(double));
1093  return d - 1.0;
1094 }
1095 
1096 template <typename Container>
1097 void Rng::shuffle(Container& container) noexcept {
1098  auto size = static_cast<uint32_t>(container.size());
1099  for (auto i = size; i > 1U; --i) {
1100  using std::swap;
1101  auto p = bounded(i); // number in [0, i)
1102  swap(container[i - 1], container[p]);
1103  }
1104 }
1105 
1106 constexpr uint64_t Rng::rotl(uint64_t x, unsigned k) noexcept {
1107  return (x << k) | (x >> (64U - k));
1108 }
1109 
1110 template <typename Op>
1112 Bench& Bench::run(Op&& op) {
1113  // It is important that this method is kept short so the compiler can do better optimizations/ inlining of op()
1114  detail::IterationLogic iterationLogic(*this);
1115  auto& pc = detail::performanceCounters();
1116 
1117  while (auto n = iterationLogic.numIters()) {
1118  pc.beginMeasure();
1119  Clock::time_point before = Clock::now();
1120  while (n-- > 0) {
1121  op();
1122  }
1123  Clock::time_point after = Clock::now();
1124  pc.endMeasure();
1125  pc.updateResults(iterationLogic.numIters());
1126  iterationLogic.add(after - before, pc);
1127  }
1128  iterationLogic.moveResultTo(mResults);
1129  return *this;
1130 }
1131 
1132 // Performs all evaluations.
1133 template <typename Op>
1134 Bench& Bench::run(char const* benchmarkName, Op&& op) {
1135  name(benchmarkName);
1136  return run(std::forward<Op>(op));
1137 }
1138 
1139 template <typename Op>
1140 Bench& Bench::run(std::string const& benchmarkName, Op&& op) {
1141  name(benchmarkName);
1142  return run(std::forward<Op>(op));
1143 }
1144 
1145 template <typename Op>
1146 BigO Bench::complexityBigO(char const* benchmarkName, Op op) const {
1147  return BigO(benchmarkName, BigO::collectRangeMeasure(mResults), op);
1148 }
1149 
1150 template <typename Op>
1151 BigO Bench::complexityBigO(std::string const& benchmarkName, Op op) const {
1152  return BigO(benchmarkName, BigO::collectRangeMeasure(mResults), op);
1153 }
1154 
1155 // Set the batch size, e.g. number of processed bytes, or some other metric for the size of the processed data in each iteration.
1156 // Any argument is cast to double.
1157 template <typename T>
1158 Bench& Bench::batch(T b) noexcept {
1159  mConfig.mBatch = static_cast<double>(b);
1160  return *this;
1161 }
1162 
1163 // Sets the computation complexity of the next run. Any argument is cast to double.
1164 template <typename T>
1165 Bench& Bench::complexityN(T n) noexcept {
1166  mConfig.mComplexityN = static_cast<double>(n);
1167  return *this;
1168 }
1169 
1170 // Convenience: makes sure none of the given arguments are optimized away by the compiler.
1171 template <typename Arg>
1173  detail::doNotOptimizeAway(std::forward<Arg>(arg));
1174  return *this;
1175 }
1176 
1177 // Makes sure none of the given arguments are optimized away by the compiler.
1178 template <typename Arg>
1179 void doNotOptimizeAway(Arg&& arg) {
1180  detail::doNotOptimizeAway(std::forward<Arg>(arg));
1181 }
1182 
1183 namespace detail {
1184 
1185 #if defined(_MSC_VER)
1186 template <typename T>
1187 void doNotOptimizeAway(T const& val) {
1188  doNotOptimizeAwaySink(&val);
1189 }
1190 
1191 #endif
1192 
1193 } // namespace detail
1194 } // namespace nanobench
1195 } // namespace ankerl
1196 
1197 #if defined(ANKERL_NANOBENCH_IMPLEMENT)
1198 
1200 // implementation part - only visible in .cpp
1202 
1203 # include <algorithm> // sort, reverse
1204 # include <atomic> // compare_exchange_strong in loop overhead
1205 # include <cstdlib> // getenv
1206 # include <cstring> // strstr, strncmp
1207 # include <fstream> // ifstream to parse proc files
1208 # include <iomanip> // setw, setprecision
1209 # include <iostream> // cout
1210 # include <numeric> // accumulate
1211 # include <random> // random_device
1212 # include <sstream> // to_s in Number
1213 # include <stdexcept> // throw for rendering templates
1214 # include <tuple> // std::tie
1215 # if defined(__linux__)
1216 # include <unistd.h> //sysconf
1217 # endif
1218 # if ANKERL_NANOBENCH(PERF_COUNTERS)
1219 # include <map> // map
1220 
1221 # include <linux/perf_event.h>
1222 # include <sys/ioctl.h>
1223 # include <sys/syscall.h>
1224 # include <unistd.h>
1225 # endif
1226 
1227 // declarations ///////////////////////////////////////////////////////////////////////////////////
1228 
1229 namespace ankerl {
1230 namespace nanobench {
1231 
1232 // helper stuff that is only intended to be used internally
1233 namespace detail {
1234 
1235 struct TableInfo;
1236 
1237 // formatting utilities
1238 namespace fmt {
1239 
1240 class NumSep;
1241 class StreamStateRestorer;
1242 class Number;
1243 class MarkDownColumn;
1244 class MarkDownCode;
1245 
1246 } // namespace fmt
1247 } // namespace detail
1248 } // namespace nanobench
1249 } // namespace ankerl
1250 
1251 // definitions ////////////////////////////////////////////////////////////////////////////////////
1252 
1253 namespace ankerl {
1254 namespace nanobench {
1255 
1256 uint64_t splitMix64(uint64_t& state) noexcept;
1257 
1258 namespace detail {
1259 
1260 // helpers to get double values
1261 template <typename T>
1262 inline double d(T t) noexcept {
1263  return static_cast<double>(t);
1264 }
1265 inline double d(Clock::duration duration) noexcept {
1266  return std::chrono::duration_cast<std::chrono::duration<double>>(duration).count();
1267 }
1268 
1269 // Calculates clock resolution once, and remembers the result
1270 inline Clock::duration clockResolution() noexcept;
1271 
1272 } // namespace detail
1273 
1274 namespace templates {
1275 
1276 char const* csv() noexcept {
1277  return R"DELIM("title";"name";"unit";"batch";"elapsed";"error %";"instructions";"branches";"branch misses";"total" {{#result}}"{{title}}";"{{name}}";"{{unit}}";{{batch}};{{median(elapsed)}};{{medianAbsolutePercentError(elapsed)}};{{median(instructions)}};{{median(branchinstructions)}};{{median(branchmisses)}};{{sumProduct(iterations, elapsed)}} {{/result}})DELIM";
1278 }
1279 
1280 char const* htmlBoxplot() noexcept {
1281  return R"DELIM(<html> <head> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </head> <body> <div id="myDiv"></div> <script> var data = [ {{#result}}{ name: '{{name}}', y: [{{#measurement}}{{elapsed}}{{^-last}}, {{/last}}{{/measurement}}], }, {{/result}} ]; var title = '{{title}}'; data = data.map(a => Object.assign(a, { boxpoints: 'all', pointpos: 0, type: 'box' })); var layout = { title: { text: title }, showlegend: false, yaxis: { title: 'time per unit', rangemode: 'tozero', autorange: true } }; Plotly.newPlot('myDiv', data, layout, {responsive: true}); </script> </body> </html>)DELIM";
1282 }
1283 
1284 char const* json() noexcept {
1285  return R"DELIM({ "results": [ {{#result}} { "title": "{{title}}", "name": "{{name}}", "unit": "{{unit}}", "batch": {{batch}}, "complexityN": {{complexityN}}, "epochs": {{epochs}}, "clockResolution": {{clockResolution}}, "clockResolutionMultiple": {{clockResolutionMultiple}}, "maxEpochTime": {{maxEpochTime}}, "minEpochTime": {{minEpochTime}}, "minEpochIterations": {{minEpochIterations}}, "epochIterations": {{epochIterations}}, "warmup": {{warmup}}, "relative": {{relative}}, "median(elapsed)": {{median(elapsed)}}, "medianAbsolutePercentError(elapsed)": {{medianAbsolutePercentError(elapsed)}}, "median(instructions)": {{median(instructions)}}, "medianAbsolutePercentError(instructions)": {{medianAbsolutePercentError(instructions)}}, "median(cpucycles)": {{median(cpucycles)}}, "median(contextswitches)": {{median(contextswitches)}}, "median(pagefaults)": {{median(pagefaults)}}, "median(branchinstructions)": {{median(branchinstructions)}}, "median(branchmisses)": {{median(branchmisses)}}, "totalTime": {{sumProduct(iterations, elapsed)}}, "measurements": [ {{#measurement}} { "iterations": {{iterations}}, "elapsed": {{elapsed}}, "pagefaults": {{pagefaults}}, "cpucycles": {{cpucycles}}, "contextswitches": {{contextswitches}}, "instructions": {{instructions}}, "branchinstructions": {{branchinstructions}}, "branchmisses": {{branchmisses}} }{{^-last}},{{/-last}} {{/measurement}} ] }{{^-last}},{{/-last}} {{/result}} ] })DELIM";
1286 }
1287 
1288 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
1289 struct Node {
1290  enum class Type { tag, content, section, inverted_section };
1291 
1292  char const* begin;
1293  char const* end;
1294  std::vector<Node> children;
1295  Type type;
1296 
1297  template <size_t N>
1298  // NOLINTNEXTLINE(hicpp-avoid-c-arrays,modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
1299  bool operator==(char const (&str)[N]) const noexcept {
1300  return static_cast<size_t>(std::distance(begin, end) + 1) == N && 0 == strncmp(str, begin, N - 1);
1301  }
1302 };
1303 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
1304 
1305 static std::vector<Node> parseMustacheTemplate(char const** tpl) {
1306  std::vector<Node> nodes;
1307 
1308  while (true) {
1309  auto begin = std::strstr(*tpl, "{{");
1310  auto end = begin;
1311  if (begin != nullptr) {
1312  begin += 2;
1313  end = std::strstr(begin, "}}");
1314  }
1315 
1316  if (begin == nullptr || end == nullptr) {
1317  // nothing found, finish node
1318  nodes.emplace_back(Node{*tpl, *tpl + std::strlen(*tpl), std::vector<Node>{}, Node::Type::content});
1319  return nodes;
1320  }
1321 
1322  nodes.emplace_back(Node{*tpl, begin - 2, std::vector<Node>{}, Node::Type::content});
1323 
1324  // we found a tag
1325  *tpl = end + 2;
1326  switch (*begin) {
1327  case '/':
1328  // finished! bail out
1329  return nodes;
1330 
1331  case '#':
1332  nodes.emplace_back(Node{begin + 1, end, parseMustacheTemplate(tpl), Node::Type::section});
1333  break;
1334 
1335  case '^':
1336  nodes.emplace_back(Node{begin + 1, end, parseMustacheTemplate(tpl), Node::Type::inverted_section});
1337  break;
1338 
1339  default:
1340  nodes.emplace_back(Node{begin, end, std::vector<Node>{}, Node::Type::tag});
1341  break;
1342  }
1343  }
1344 }
1345 
1346 static bool generateFirstLast(Node const& n, size_t idx, size_t size, std::ostream& out) {
1347  bool matchFirst = n == "-first";
1348  bool matchLast = n == "-last";
1349  if (!matchFirst && !matchLast) {
1350  return false;
1351  }
1352 
1353  bool doWrite = false;
1354  if (n.type == Node::Type::section) {
1355  doWrite = (matchFirst && idx == 0) || (matchLast && idx == size - 1);
1356  } else if (n.type == Node::Type::inverted_section) {
1357  doWrite = (matchFirst && idx != 0) || (matchLast && idx != size - 1);
1358  }
1359 
1360  if (doWrite) {
1361  for (auto const& child : n.children) {
1362  if (child.type == Node::Type::content) {
1363  out.write(child.begin, std::distance(child.begin, child.end));
1364  }
1365  }
1366  }
1367  return true;
1368 }
1369 
1370 static bool matchCmdArgs(std::string const& str, std::vector<std::string>& matchResult) {
1371  matchResult.clear();
1372  auto idxOpen = str.find('(');
1373  auto idxClose = str.find(')', idxOpen);
1374  if (idxClose == std::string::npos) {
1375  return false;
1376  }
1377 
1378  matchResult.emplace_back(str.substr(0, idxOpen));
1379 
1380  // split by comma
1381  matchResult.emplace_back(std::string{});
1382  for (size_t i = idxOpen + 1; i != idxClose; ++i) {
1383  if (str[i] == ' ' || str[i] == '\t') {
1384  // skip whitespace
1385  continue;
1386  }
1387  if (str[i] == ',') {
1388  // got a comma => new string
1389  matchResult.emplace_back(std::string{});
1390  continue;
1391  }
1392  // no whitespace no comma, append
1393  matchResult.back() += str[i];
1394  }
1395  return true;
1396 }
1397 
1398 static bool generateConfigTag(Node const& n, Config const& config, std::ostream& out) {
1399  using detail::d;
1400 
1401  if (n == "title") {
1402  out << config.mBenchmarkTitle;
1403  return true;
1404  } else if (n == "name") {
1405  out << config.mBenchmarkName;
1406  return true;
1407  } else if (n == "unit") {
1408  out << config.mUnit;
1409  return true;
1410  } else if (n == "batch") {
1411  out << config.mBatch;
1412  return true;
1413  } else if (n == "complexityN") {
1414  out << config.mComplexityN;
1415  return true;
1416  } else if (n == "epochs") {
1417  out << config.mNumEpochs;
1418  return true;
1419  } else if (n == "clockResolution") {
1420  out << d(detail::clockResolution());
1421  return true;
1422  } else if (n == "clockResolutionMultiple") {
1423  out << config.mClockResolutionMultiple;
1424  return true;
1425  } else if (n == "maxEpochTime") {
1426  out << d(config.mMaxEpochTime);
1427  return true;
1428  } else if (n == "minEpochTime") {
1429  out << d(config.mMinEpochTime);
1430  return true;
1431  } else if (n == "minEpochIterations") {
1432  out << config.mMinEpochIterations;
1433  return true;
1434  } else if (n == "epochIterations") {
1435  out << config.mEpochIterations;
1436  return true;
1437  } else if (n == "warmup") {
1438  out << config.mWarmup;
1439  return true;
1440  } else if (n == "relative") {
1441  out << config.mIsRelative;
1442  return true;
1443  }
1444  return false;
1445 }
1446 
1447 static std::ostream& generateResultTag(Node const& n, Result const& r, std::ostream& out) {
1448  if (generateConfigTag(n, r.config(), out)) {
1449  return out;
1450  }
1451  // match e.g. "median(elapsed)"
1452  // g++ 4.8 doesn't implement std::regex :(
1453  // static std::regex const regOpArg1("^([a-zA-Z]+)\\(([a-zA-Z]*)\\)$");
1454  // std::cmatch matchResult;
1455  // if (std::regex_match(n.begin, n.end, matchResult, regOpArg1)) {
1456  std::vector<std::string> matchResult;
1457  if (matchCmdArgs(std::string(n.begin, n.end), matchResult)) {
1458  if (matchResult.size() == 2) {
1459  auto m = Result::fromString(matchResult[1]);
1460  if (m == Result::Measure::_size) {
1461  return out << 0.0;
1462  }
1463 
1464  if (matchResult[0] == "median") {
1465  return out << r.median(m);
1466  }
1467  if (matchResult[0] == "average") {
1468  return out << r.average(m);
1469  }
1470  if (matchResult[0] == "medianAbsolutePercentError") {
1471  return out << r.medianAbsolutePercentError(m);
1472  }
1473  if (matchResult[0] == "sum") {
1474  return out << r.sum(m);
1475  }
1476  if (matchResult[0] == "minimum") {
1477  return out << r.minimum(m);
1478  }
1479  if (matchResult[0] == "maximum") {
1480  return out << r.maximum(m);
1481  }
1482  } else if (matchResult.size() == 3) {
1483  auto m1 = Result::fromString(matchResult[1]);
1484  auto m2 = Result::fromString(matchResult[2]);
1485  if (m1 == Result::Measure::_size || m2 == Result::Measure::_size) {
1486  return out << 0.0;
1487  }
1488 
1489  if (matchResult[0] == "sumProduct") {
1490  return out << r.sumProduct(m1, m2);
1491  }
1492  }
1493  }
1494 
1495  // match e.g. "sumProduct(elapsed, iterations)"
1496  // static std::regex const regOpArg2("^([a-zA-Z]+)\\(([a-zA-Z]*)\\s*,\\s+([a-zA-Z]*)\\)$");
1497 
1498  // nothing matches :(
1499  throw std::runtime_error("command '" + std::string(n.begin, n.end) + "' not understood");
1500 }
1501 
1502 static void generateResultMeasurement(std::vector<Node> const& nodes, size_t idx, Result const& r, std::ostream& out) {
1503  for (auto const& n : nodes) {
1504  if (!generateFirstLast(n, idx, r.size(), out)) {
1505  ANKERL_NANOBENCH_LOG("n.type=" << static_cast<int>(n.type));
1506  switch (n.type) {
1507  case Node::Type::content:
1508  out.write(n.begin, std::distance(n.begin, n.end));
1509  break;
1510 
1511  case Node::Type::inverted_section:
1512  throw std::runtime_error("got a inverted section inside measurement");
1513 
1514  case Node::Type::section:
1515  throw std::runtime_error("got a section inside measurement");
1516 
1517  case Node::Type::tag: {
1518  auto m = Result::fromString(std::string(n.begin, n.end));
1519  if (m == Result::Measure::_size || !r.has(m)) {
1520  out << 0.0;
1521  } else {
1522  out << r.get(idx, m);
1523  }
1524  break;
1525  }
1526  }
1527  }
1528  }
1529 }
1530 
1531 static void generateResult(std::vector<Node> const& nodes, size_t idx, std::vector<Result> const& results, std::ostream& out) {
1532  auto const& r = results[idx];
1533  for (auto const& n : nodes) {
1534  if (!generateFirstLast(n, idx, results.size(), out)) {
1535  ANKERL_NANOBENCH_LOG("n.type=" << static_cast<int>(n.type));
1536  switch (n.type) {
1537  case Node::Type::content:
1538  out.write(n.begin, std::distance(n.begin, n.end));
1539  break;
1540 
1541  case Node::Type::inverted_section:
1542  throw std::runtime_error("got a inverted section inside result");
1543 
1544  case Node::Type::section:
1545  if (n == "measurement") {
1546  for (size_t i = 0; i < r.size(); ++i) {
1547  generateResultMeasurement(n.children, i, r, out);
1548  }
1549  } else {
1550  throw std::runtime_error("got a section inside result");
1551  }
1552  break;
1553 
1554  case Node::Type::tag:
1555  generateResultTag(n, r, out);
1556  break;
1557  }
1558  }
1559  }
1560 }
1561 
1562 } // namespace templates
1563 
1564 // helper stuff that only intended to be used internally
1565 namespace detail {
1566 
1567 char const* getEnv(char const* name);
1568 bool isEndlessRunning(std::string const& name);
1569 
1570 template <typename T>
1571 T parseFile(std::string const& filename);
1572 
1573 void gatherStabilityInformation(std::vector<std::string>& warnings, std::vector<std::string>& recommendations);
1574 void printStabilityInformationOnce(std::ostream* os);
1575 
1576 // remembers the last table settings used. When it changes, a new table header is automatically written for the new entry.
1577 uint64_t& singletonHeaderHash() noexcept;
1578 
1579 // determines resolution of the given clock. This is done by measuring multiple times and returning the minimum time difference.
1580 Clock::duration calcClockResolution(size_t numEvaluations) noexcept;
1581 
1582 // formatting utilities
1583 namespace fmt {
1584 
1585 // adds thousands separator to numbers
1586 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
1587 class NumSep : public std::numpunct<char> {
1588 public:
1589  explicit NumSep(char sep);
1590  char do_thousands_sep() const override;
1591  std::string do_grouping() const override;
1592 
1593 private:
1594  char mSep;
1595 };
1596 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
1597 
1598 // RAII to save & restore a stream's state
1599 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
1600 class StreamStateRestorer {
1601 public:
1602  explicit StreamStateRestorer(std::ostream& s);
1603  ~StreamStateRestorer();
1604 
1605  // sets back all stream info that we remembered at construction
1606  void restore();
1607 
1608  // don't allow copying / moving
1609  StreamStateRestorer(StreamStateRestorer const&) = delete;
1610  StreamStateRestorer& operator=(StreamStateRestorer const&) = delete;
1611  StreamStateRestorer(StreamStateRestorer&&) = delete;
1612  StreamStateRestorer& operator=(StreamStateRestorer&&) = delete;
1613 
1614 private:
1615  std::ostream& mStream;
1616  std::locale mLocale;
1617  std::streamsize const mPrecision;
1618  std::streamsize const mWidth;
1619  std::ostream::char_type const mFill;
1620  std::ostream::fmtflags const mFmtFlags;
1621 };
1622 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
1623 
1624 // Number formatter
1625 class Number {
1626 public:
1627  Number(int width, int precision, double value);
1628  Number(int width, int precision, int64_t value);
1629  std::string to_s() const;
1630 
1631 private:
1632  friend std::ostream& operator<<(std::ostream& os, Number const& n);
1633  std::ostream& write(std::ostream& os) const;
1634 
1635  int mWidth;
1636  int mPrecision;
1637  double mValue;
1638 };
1639 
1640 // helper replacement for std::to_string of signed/unsigned numbers so we are locale independent
1641 std::string to_s(uint64_t s);
1642 
1643 std::ostream& operator<<(std::ostream& os, Number const& n);
1644 
1645 class MarkDownColumn {
1646 public:
1647  MarkDownColumn(int w, int prec, std::string const& tit, std::string const& suff, double val);
1648  std::string title() const;
1649  std::string separator() const;
1650  std::string invalid() const;
1651  std::string value() const;
1652 
1653 private:
1654  int mWidth;
1655  int mPrecision;
1656  std::string mTitle;
1657  std::string mSuffix;
1658  double mValue;
1659 };
1660 
1661 // Formats any text as markdown code, escaping backticks.
1662 class MarkDownCode {
1663 public:
1664  explicit MarkDownCode(std::string const& what);
1665 
1666 private:
1667  friend std::ostream& operator<<(std::ostream& os, MarkDownCode const& mdCode);
1668  std::ostream& write(std::ostream& os) const;
1669 
1670  std::string mWhat{};
1671 };
1672 
1673 std::ostream& operator<<(std::ostream& os, MarkDownCode const& mdCode);
1674 
1675 } // namespace fmt
1676 } // namespace detail
1677 } // namespace nanobench
1678 } // namespace ankerl
1679 
1680 // implementation /////////////////////////////////////////////////////////////////////////////////
1681 
1682 namespace ankerl {
1683 namespace nanobench {
1684 
1685 void render(char const* mustacheTemplate, std::vector<Result> const& results, std::ostream& out) {
1686  detail::fmt::StreamStateRestorer restorer(out);
1687 
1688  out.precision(std::numeric_limits<double>::digits10);
1689  auto nodes = templates::parseMustacheTemplate(&mustacheTemplate);
1690 
1691  for (auto const& n : nodes) {
1692  ANKERL_NANOBENCH_LOG("n.type=" << static_cast<int>(n.type));
1693  switch (n.type) {
1694  case templates::Node::Type::content:
1695  out.write(n.begin, std::distance(n.begin, n.end));
1696  break;
1697 
1698  case templates::Node::Type::inverted_section:
1699  throw std::runtime_error("unknown list '" + std::string(n.begin, n.end) + "'");
1700 
1701  case templates::Node::Type::section:
1702  if (n == "result") {
1703  const size_t nbResults = results.size();
1704  for (size_t i = 0; i < nbResults; ++i) {
1705  generateResult(n.children, i, results, out);
1706  }
1707  } else {
1708  throw std::runtime_error("unknown section '" + std::string(n.begin, n.end) + "'");
1709  }
1710  break;
1711 
1712  case templates::Node::Type::tag:
1713  // This just uses the last result's config.
1714  if (!generateConfigTag(n, results.back().config(), out)) {
1715  throw std::runtime_error("unknown tag '" + std::string(n.begin, n.end) + "'");
1716  }
1717  break;
1718  }
1719  }
1720 }
1721 
1722 void render(char const* mustacheTemplate, const Bench& bench, std::ostream& out) {
1723  render(mustacheTemplate, bench.results(), out);
1724 }
1725 
1726 namespace detail {
1727 
1728 PerformanceCounters& performanceCounters() {
1729 # if defined(__clang__)
1730 # pragma clang diagnostic push
1731 # pragma clang diagnostic ignored "-Wexit-time-destructors"
1732 # endif
1733  static PerformanceCounters pc;
1734 # if defined(__clang__)
1735 # pragma clang diagnostic pop
1736 # endif
1737  return pc;
1738 }
1739 
1740 // Windows version of doNotOptimizeAway
1741 // see https://github.com/google/benchmark/blob/master/include/benchmark/benchmark.h#L307
1742 // see https://github.com/facebook/folly/blob/master/folly/Benchmark.h#L280
1743 // see https://docs.microsoft.com/en-us/cpp/preprocessor/optimize
1744 # if defined(_MSC_VER)
1745 # pragma optimize("", off)
1746 void doNotOptimizeAwaySink(void const*) {}
1747 # pragma optimize("", on)
1748 # endif
1749 
1750 template <typename T>
1751 T parseFile(std::string const& filename) {
1752  std::ifstream fin(filename);
1753  T num{};
1754  fin >> num;
1755  return num;
1756 }
1757 
1758 char const* getEnv(char const* name) {
1759 # if defined(_MSC_VER)
1760 # pragma warning(push)
1761 # pragma warning(disable : 4996) // getenv': This function or variable may be unsafe.
1762 # endif
1763  return std::getenv(name);
1764 # if defined(_MSC_VER)
1765 # pragma warning(pop)
1766 # endif
1767 }
1768 
1769 bool isEndlessRunning(std::string const& name) {
1770  auto endless = getEnv("NANOBENCH_ENDLESS");
1771  return nullptr != endless && endless == name;
1772 }
1773 
1774 void gatherStabilityInformation(std::vector<std::string>& warnings, std::vector<std::string>& recommendations) {
1775  warnings.clear();
1776  recommendations.clear();
1777 
1778  bool recommendCheckFlags = false;
1779 
1780 # if defined(DEBUG)
1781  warnings.emplace_back("DEBUG defined");
1782  recommendCheckFlags = true;
1783 # endif
1784 
1785  bool recommendPyPerf = false;
1786 # if defined(__linux__)
1787  auto nprocs = sysconf(_SC_NPROCESSORS_CONF);
1788  if (nprocs <= 0) {
1789  warnings.emplace_back("couldn't figure out number of processors - no governor, turbo check possible");
1790  } else {
1791 
1792  // check frequency scaling
1793  for (long id = 0; id < nprocs; ++id) {
1794  auto idStr = detail::fmt::to_s(static_cast<uint64_t>(id));
1795  auto sysCpu = "/sys/devices/system/cpu/cpu" + idStr;
1796  auto minFreq = parseFile<int64_t>(sysCpu + "/cpufreq/scaling_min_freq");
1797  auto maxFreq = parseFile<int64_t>(sysCpu + "/cpufreq/scaling_max_freq");
1798  if (minFreq != maxFreq) {
1799  auto minMHz = static_cast<double>(minFreq) / 1000.0;
1800  auto maxMHz = static_cast<double>(maxFreq) / 1000.0;
1801  warnings.emplace_back("CPU frequency scaling enabled: CPU " + idStr + " between " +
1802  detail::fmt::Number(1, 1, minMHz).to_s() + " and " + detail::fmt::Number(1, 1, maxMHz).to_s() +
1803  " MHz");
1804  recommendPyPerf = true;
1805  break;
1806  }
1807  }
1808 
1809  auto currentGovernor = parseFile<std::string>("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor");
1810  if ("performance" != currentGovernor) {
1811  warnings.emplace_back("CPU governor is '" + currentGovernor + "' but should be 'performance'");
1812  recommendPyPerf = true;
1813  }
1814 
1815  if (0 == parseFile<int>("/sys/devices/system/cpu/intel_pstate/no_turbo")) {
1816  warnings.emplace_back("Turbo is enabled, CPU frequency will fluctuate");
1817  recommendPyPerf = true;
1818  }
1819  }
1820 # endif
1821 
1822  if (recommendCheckFlags) {
1823  recommendations.emplace_back("Make sure you compile for Release");
1824  }
1825  if (recommendPyPerf) {
1826  recommendations.emplace_back("Use 'pyperf system tune' before benchmarking. See https://github.com/vstinner/pyperf");
1827  }
1828 }
1829 
1830 void printStabilityInformationOnce(std::ostream* outStream) {
1831  static bool shouldPrint = true;
1832  if (shouldPrint && outStream) {
1833  auto& os = *outStream;
1834  shouldPrint = false;
1835  std::vector<std::string> warnings;
1836  std::vector<std::string> recommendations;
1837  gatherStabilityInformation(warnings, recommendations);
1838  if (warnings.empty()) {
1839  return;
1840  }
1841 
1842  os << "Warning, results might be unstable:" << std::endl;
1843  for (auto const& w : warnings) {
1844  os << "* " << w << std::endl;
1845  }
1846 
1847  os << std::endl << "Recommendations" << std::endl;
1848  for (auto const& r : recommendations) {
1849  os << "* " << r << std::endl;
1850  }
1851  }
1852 }
1853 
1854 // remembers the last table settings used. When it changes, a new table header is automatically written for the new entry.
1855 uint64_t& singletonHeaderHash() noexcept {
1856  static uint64_t sHeaderHash{};
1857  return sHeaderHash;
1858 }
1859 
1861 inline uint64_t fnv1a(std::string const& str) noexcept {
1862  auto val = UINT64_C(14695981039346656037);
1863  for (auto c : str) {
1864  val = (val ^ static_cast<uint8_t>(c)) * UINT64_C(1099511628211);
1865  }
1866  return val;
1867 }
1868 
1870 inline uint64_t hash_combine(uint64_t seed, uint64_t val) {
1871  return seed ^ (val + UINT64_C(0x9e3779b9) + (seed << 6U) + (seed >> 2U));
1872 }
1873 
1874 // determines resolution of the given clock. This is done by measuring multiple times and returning the minimum time difference.
1875 Clock::duration calcClockResolution(size_t numEvaluations) noexcept {
1876  auto bestDuration = Clock::duration::max();
1877  Clock::time_point tBegin;
1878  Clock::time_point tEnd;
1879  for (size_t i = 0; i < numEvaluations; ++i) {
1880  tBegin = Clock::now();
1881  do {
1882  tEnd = Clock::now();
1883  } while (tBegin == tEnd);
1884  bestDuration = (std::min)(bestDuration, tEnd - tBegin);
1885  }
1886  return bestDuration;
1887 }
1888 
1889 // Calculates clock resolution once, and remembers the result
1890 Clock::duration clockResolution() noexcept {
1891  static Clock::duration sResolution = calcClockResolution(20);
1892  return sResolution;
1893 }
1894 
1895 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
1896 struct IterationLogic::Impl {
1897  enum class State { warmup, upscaling_runtime, measuring, endless };
1898 
1899  explicit Impl(Bench const& bench)
1900  : mBench(bench)
1901  , mResult(bench.config()) {
1902  printStabilityInformationOnce(mBench.output());
1903 
1904  // determine target runtime per epoch
1905  mTargetRuntimePerEpoch = detail::clockResolution() * mBench.clockResolutionMultiple();
1906  if (mTargetRuntimePerEpoch > mBench.maxEpochTime()) {
1907  mTargetRuntimePerEpoch = mBench.maxEpochTime();
1908  }
1909  if (mTargetRuntimePerEpoch < mBench.minEpochTime()) {
1910  mTargetRuntimePerEpoch = mBench.minEpochTime();
1911  }
1912 
1913  if (isEndlessRunning(mBench.name())) {
1914  std::cerr << "NANOBENCH_ENDLESS set: running '" << mBench.name() << "' endlessly" << std::endl;
1915  mNumIters = (std::numeric_limits<uint64_t>::max)();
1916  mState = State::endless;
1917  } else if (0 != mBench.warmup()) {
1918  mNumIters = mBench.warmup();
1919  mState = State::warmup;
1920  } else if (0 != mBench.epochIterations()) {
1921  // exact number of iterations
1922  mNumIters = mBench.epochIterations();
1923  mState = State::measuring;
1924  } else {
1925  mNumIters = mBench.minEpochIterations();
1926  mState = State::upscaling_runtime;
1927  }
1928  }
1929 
1930  // directly calculates new iters based on elapsed&iters, and adds a 10% noise. Makes sure we don't underflow.
1931  ANKERL_NANOBENCH(NODISCARD) uint64_t calcBestNumIters(std::chrono::nanoseconds elapsed, uint64_t iters) noexcept {
1932  auto doubleElapsed = d(elapsed);
1933  auto doubleTargetRuntimePerEpoch = d(mTargetRuntimePerEpoch);
1934  auto doubleNewIters = doubleTargetRuntimePerEpoch / doubleElapsed * d(iters);
1935 
1936  auto doubleMinEpochIters = d(mBench.minEpochIterations());
1937  if (doubleNewIters < doubleMinEpochIters) {
1938  doubleNewIters = doubleMinEpochIters;
1939  }
1940  doubleNewIters *= 1.0 + 0.2 * mRng.uniform01();
1941 
1942  // +0.5 for correct rounding when casting
1943  // NOLINTNEXTLINE(bugprone-incorrect-roundings)
1944  return static_cast<uint64_t>(doubleNewIters + 0.5);
1945  }
1946 
1947  ANKERL_NANOBENCH_NO_SANITIZE("integer") void upscale(std::chrono::nanoseconds elapsed) {
1948  if (elapsed * 10 < mTargetRuntimePerEpoch) {
1949  // we are far below the target runtime. Multiply iterations by 10 (with overflow check)
1950  if (mNumIters * 10 < mNumIters) {
1951  // overflow :-(
1952  showResult("iterations overflow. Maybe your code got optimized away?");
1953  mNumIters = 0;
1954  return;
1955  }
1956  mNumIters *= 10;
1957  } else {
1958  mNumIters = calcBestNumIters(elapsed, mNumIters);
1959  }
1960  }
1961 
1962  void add(std::chrono::nanoseconds elapsed, PerformanceCounters const& pc) noexcept {
1963 # if defined(ANKERL_NANOBENCH_LOG_ENABLED)
1964  auto oldIters = mNumIters;
1965 # endif
1966 
1967  switch (mState) {
1968  case State::warmup:
1969  if (isCloseEnoughForMeasurements(elapsed)) {
1970  // if elapsed is close enough, we can skip upscaling and go right to measurements
1971  // still, we don't add the result to the measurements.
1972  mState = State::measuring;
1973  mNumIters = calcBestNumIters(elapsed, mNumIters);
1974  } else {
1975  // not close enough: switch to upscaling
1976  mState = State::upscaling_runtime;
1977  upscale(elapsed);
1978  }
1979  break;
1980 
1981  case State::upscaling_runtime:
1982  if (isCloseEnoughForMeasurements(elapsed)) {
1983  // if we are close enough, add measurement and switch to always measuring
1984  mState = State::measuring;
1985  mTotalElapsed += elapsed;
1986  mTotalNumIters += mNumIters;
1987  mResult.add(elapsed, mNumIters, pc);
1988  mNumIters = calcBestNumIters(mTotalElapsed, mTotalNumIters);
1989  } else {
1990  upscale(elapsed);
1991  }
1992  break;
1993 
1994  case State::measuring:
1995  // just add measurements - no questions asked. Even when runtime is low. But we can't ignore
1996  // that fluctuation, or else we would bias the result
1997  mTotalElapsed += elapsed;
1998  mTotalNumIters += mNumIters;
1999  mResult.add(elapsed, mNumIters, pc);
2000  if (0 != mBench.epochIterations()) {
2001  mNumIters = mBench.epochIterations();
2002  } else {
2003  mNumIters = calcBestNumIters(mTotalElapsed, mTotalNumIters);
2004  }
2005  break;
2006 
2007  case State::endless:
2008  mNumIters = (std::numeric_limits<uint64_t>::max)();
2009  break;
2010  }
2011 
2012  if (static_cast<uint64_t>(mResult.size()) == mBench.epochs()) {
2013  // we got all the results that we need, finish it
2014  showResult("");
2015  mNumIters = 0;
2016  }
2017 
2018  ANKERL_NANOBENCH_LOG(mBench.name() << ": " << detail::fmt::Number(20, 3, static_cast<double>(elapsed.count())) << " elapsed, "
2019  << detail::fmt::Number(20, 3, static_cast<double>(mTargetRuntimePerEpoch.count()))
2020  << " target. oldIters=" << oldIters << ", mNumIters=" << mNumIters
2021  << ", mState=" << static_cast<int>(mState));
2022  }
2023 
2024  void showResult(std::string const& errorMessage) const {
2025  ANKERL_NANOBENCH_LOG(errorMessage);
2026 
2027  if (mBench.output() != nullptr) {
2028  // prepare column data ///////
2029  std::vector<fmt::MarkDownColumn> columns;
2030 
2031  auto rMedian = mResult.median(Result::Measure::elapsed);
2032 
2033  if (mBench.relative()) {
2034  double d = 100.0;
2035  if (!mBench.results().empty()) {
2036  d = rMedian <= 0.0 ? 0.0 : mBench.results().front().median(Result::Measure::elapsed) / rMedian * 100.0;
2037  }
2038  columns.emplace_back(11, 1, "relative", "%", d);
2039  }
2040 
2041  if (mBench.complexityN() > 0) {
2042  columns.emplace_back(14, 0, "complexityN", "", mBench.complexityN());
2043  }
2044 
2045  columns.emplace_back(22, 2, "ns/" + mBench.unit(), "", 1e9 * rMedian / mBench.batch());
2046  columns.emplace_back(22, 2, mBench.unit() + "/s", "", rMedian <= 0.0 ? 0.0 : mBench.batch() / rMedian);
2047 
2048  double rErrorMedian = mResult.medianAbsolutePercentError(Result::Measure::elapsed);
2049  columns.emplace_back(10, 1, "err%", "%", rErrorMedian * 100.0);
2050 
2051  double rInsMedian = -1.0;
2052  if (mResult.has(Result::Measure::instructions)) {
2053  rInsMedian = mResult.median(Result::Measure::instructions);
2054  columns.emplace_back(18, 2, "ins/" + mBench.unit(), "", rInsMedian / mBench.batch());
2055  }
2056 
2057  double rCycMedian = -1.0;
2058  if (mResult.has(Result::Measure::cpucycles)) {
2059  rCycMedian = mResult.median(Result::Measure::cpucycles);
2060  columns.emplace_back(18, 2, "cyc/" + mBench.unit(), "", rCycMedian / mBench.batch());
2061  }
2062  if (rInsMedian > 0.0 && rCycMedian > 0.0) {
2063  columns.emplace_back(9, 3, "IPC", "", rCycMedian <= 0.0 ? 0.0 : rInsMedian / rCycMedian);
2064  }
2065  if (mResult.has(Result::Measure::branchinstructions)) {
2066  double rBraMedian = mResult.median(Result::Measure::branchinstructions);
2067  columns.emplace_back(17, 2, "bra/" + mBench.unit(), "", rBraMedian / mBench.batch());
2068  if (mResult.has(Result::Measure::branchmisses)) {
2069  double p = 0.0;
2070  if (rBraMedian >= 1e-9) {
2071  p = 100.0 * mResult.median(Result::Measure::branchmisses) / rBraMedian;
2072  }
2073  columns.emplace_back(10, 1, "miss%", "%", p);
2074  }
2075  }
2076 
2077  columns.emplace_back(12, 2, "total", "", mResult.sum(Result::Measure::elapsed));
2078 
2079  // write everything
2080  auto& os = *mBench.output();
2081 
2082  uint64_t hash = 0;
2083  hash = hash_combine(fnv1a(mBench.unit()), hash);
2084  hash = hash_combine(fnv1a(mBench.title()), hash);
2085  hash = hash_combine(mBench.relative(), hash);
2086  hash = hash_combine(mBench.performanceCounters(), hash);
2087 
2088  if (hash != singletonHeaderHash()) {
2089  singletonHeaderHash() = hash;
2090 
2091  // no result yet, print header
2092  os << std::endl;
2093  for (auto const& col : columns) {
2094  os << col.title();
2095  }
2096  os << "| " << mBench.title() << std::endl;
2097 
2098  for (auto const& col : columns) {
2099  os << col.separator();
2100  }
2101  os << "|:" << std::string(mBench.title().size() + 1U, '-') << std::endl;
2102  }
2103 
2104  if (!errorMessage.empty()) {
2105  for (auto const& col : columns) {
2106  os << col.invalid();
2107  }
2108  os << "| :boom: " << fmt::MarkDownCode(mBench.name()) << " (" << errorMessage << ')' << std::endl;
2109  } else {
2110  for (auto const& col : columns) {
2111  os << col.value();
2112  }
2113  os << "| ";
2114  auto showUnstable = rErrorMedian >= 0.05;
2115  if (showUnstable) {
2116  os << ":wavy_dash: ";
2117  }
2118  os << fmt::MarkDownCode(mBench.name());
2119  if (showUnstable) {
2120  auto avgIters = static_cast<double>(mTotalNumIters) / static_cast<double>(mBench.epochs());
2121  // NOLINTNEXTLINE(bugprone-incorrect-roundings)
2122  auto suggestedIters = static_cast<uint64_t>(avgIters * 10 + 0.5);
2123 
2124  os << " (Unstable with ~" << detail::fmt::Number(1, 1, avgIters)
2125  << " iters. Increase `minEpochIterations` to e.g. " << suggestedIters << ")";
2126  }
2127  os << std::endl;
2128  }
2129  }
2130  }
2131 
2132  ANKERL_NANOBENCH(NODISCARD) bool isCloseEnoughForMeasurements(std::chrono::nanoseconds elapsed) const noexcept {
2133  return elapsed * 3 >= mTargetRuntimePerEpoch * 2;
2134  }
2135 
2136  uint64_t mNumIters = 1;
2137  Bench const& mBench;
2138  std::chrono::nanoseconds mTargetRuntimePerEpoch{};
2139  Result mResult;
2140  Rng mRng{123};
2141  std::chrono::nanoseconds mTotalElapsed{};
2142  uint64_t mTotalNumIters = 0;
2143 
2144  State mState = State::upscaling_runtime;
2145 };
2146 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
2147 
2148 IterationLogic::IterationLogic(Bench const& bench) noexcept
2149  : mPimpl(new Impl(bench)) {}
2150 
2151 IterationLogic::~IterationLogic() {
2152  if (mPimpl) {
2153  delete mPimpl;
2154  }
2155 }
2156 
2157 uint64_t IterationLogic::numIters() const noexcept {
2158  ANKERL_NANOBENCH_LOG(mPimpl->mBench.name() << ": mNumIters=" << mPimpl->mNumIters);
2159  return mPimpl->mNumIters;
2160 }
2161 
2162 void IterationLogic::add(std::chrono::nanoseconds elapsed, PerformanceCounters const& pc) noexcept {
2163  mPimpl->add(elapsed, pc);
2164 }
2165 
2166 void IterationLogic::moveResultTo(std::vector<Result>& results) noexcept {
2167  results.emplace_back(std::move(mPimpl->mResult));
2168 }
2169 
2170 # if ANKERL_NANOBENCH(PERF_COUNTERS)
2171 
2172 ANKERL_NANOBENCH(IGNORE_PADDED_PUSH)
2173 class LinuxPerformanceCounters {
2174 public:
2175  struct Target {
2176  Target(uint64_t* targetValue_, bool correctMeasuringOverhead_, bool correctLoopOverhead_)
2177  : targetValue(targetValue_)
2178  , correctMeasuringOverhead(correctMeasuringOverhead_)
2179  , correctLoopOverhead(correctLoopOverhead_) {}
2180 
2181  uint64_t* targetValue{};
2182  bool correctMeasuringOverhead{};
2183  bool correctLoopOverhead{};
2184  };
2185 
2186  ~LinuxPerformanceCounters();
2187 
2188  // quick operation
2189  inline void start() {}
2190 
2191  inline void stop() {}
2192 
2193  bool monitor(perf_sw_ids swId, Target target);
2194  bool monitor(perf_hw_id hwId, Target target);
2195 
2196  bool hasError() const noexcept {
2197  return mHasError;
2198  }
2199 
2200  // Just reading data is faster than enable & disabling.
2201  // we subtract data ourselves.
2202  inline void beginMeasure() {
2203  if (mHasError) {
2204  return;
2205  }
2206 
2207  // NOLINTNEXTLINE(hicpp-signed-bitwise)
2208  mHasError = -1 == ioctl(mFd, PERF_EVENT_IOC_RESET, PERF_IOC_FLAG_GROUP);
2209  if (mHasError) {
2210  return;
2211  }
2212 
2213  // NOLINTNEXTLINE(hicpp-signed-bitwise)
2214  mHasError = -1 == ioctl(mFd, PERF_EVENT_IOC_ENABLE, PERF_IOC_FLAG_GROUP);
2215  }
2216 
2217  inline void endMeasure() {
2218  if (mHasError) {
2219  return;
2220  }
2221 
2222  // NOLINTNEXTLINE(hicpp-signed-bitwise)
2223  mHasError = (-1 == ioctl(mFd, PERF_EVENT_IOC_DISABLE, PERF_IOC_FLAG_GROUP));
2224  if (mHasError) {
2225  return;
2226  }
2227 
2228  auto const numBytes = sizeof(uint64_t) * mCounters.size();
2229  auto ret = read(mFd, mCounters.data(), numBytes);
2230  mHasError = ret != static_cast<ssize_t>(numBytes);
2231  }
2232 
2233  void updateResults(uint64_t numIters);
2234 
2235  // rounded integer division
2236  template <typename T>
2237  static inline T divRounded(T a, T divisor) {
2238  return (a + divisor / 2) / divisor;
2239  }
2240 
2241  template <typename Op>
2242  ANKERL_NANOBENCH_NO_SANITIZE("integer")
2243  void calibrate(Op&& op) {
2244  // clear current calibration data,
2245  for (auto& v : mCalibratedOverhead) {
2246  v = UINT64_C(0);
2247  }
2248 
2249  // create new calibration data
2250  auto newCalibration = mCalibratedOverhead;
2251  for (auto& v : newCalibration) {
2252  v = (std::numeric_limits<uint64_t>::max)();
2253  }
2254  for (size_t iter = 0; iter < 100; ++iter) {
2255  beginMeasure();
2256  op();
2257  endMeasure();
2258  if (mHasError) {
2259  return;
2260  }
2261 
2262  for (size_t i = 0; i < newCalibration.size(); ++i) {
2263  auto diff = mCounters[i];
2264  if (newCalibration[i] > diff) {
2265  newCalibration[i] = diff;
2266  }
2267  }
2268  }
2269 
2270  mCalibratedOverhead = std::move(newCalibration);
2271 
2272  {
2273  // calibrate loop overhead. For branches & instructions this makes sense, not so much for everything else like cycles.
2274  // marsaglia's xorshift: mov, sal/shr, xor. Times 3.
2275  // This has the nice property that the compiler doesn't seem to be able to optimize multiple calls any further.
2276  // see https://godbolt.org/z/49RVQ5
2277  uint64_t const numIters = 100000U + (std::random_device{}() & 3);
2278  uint64_t n = numIters;
2279  uint32_t x = 1234567;
2280  auto fn = [&]() {
2281  x ^= x << 13;
2282  x ^= x >> 17;
2283  x ^= x << 5;
2284  };
2285 
2286  beginMeasure();
2287  while (n-- > 0) {
2288  fn();
2289  }
2290  endMeasure();
2292  auto measure1 = mCounters;
2293 
2294  n = numIters;
2295  beginMeasure();
2296  while (n-- > 0) {
2297  // we now run *twice* so we can easily calculate the overhead
2298  fn();
2299  fn();
2300  }
2301  endMeasure();
2303  auto measure2 = mCounters;
2304 
2305  for (size_t i = 0; i < mCounters.size(); ++i) {
2306  // factor 2 because we have two instructions per loop
2307  auto m1 = measure1[i] > mCalibratedOverhead[i] ? measure1[i] - mCalibratedOverhead[i] : 0;
2308  auto m2 = measure2[i] > mCalibratedOverhead[i] ? measure2[i] - mCalibratedOverhead[i] : 0;
2309  auto overhead = m1 * 2 > m2 ? m1 * 2 - m2 : 0;
2310 
2311  mLoopOverhead[i] = divRounded(overhead, numIters);
2312  }
2313  }
2314  }
2315 
2316 private:
2317  bool monitor(uint32_t type, uint64_t eventid, Target target);
2318 
2319  std::map<uint64_t, Target> mIdToTarget{};
2320 
2321  // start with minimum size of 3 for read_format
2322  std::vector<uint64_t> mCounters{3};
2323  std::vector<uint64_t> mCalibratedOverhead{3};
2324  std::vector<uint64_t> mLoopOverhead{3};
2325 
2326  uint64_t mTimeEnabledNanos = 0;
2327  uint64_t mTimeRunningNanos = 0;
2328  int mFd = -1;
2329  bool mHasError = false;
2330 };
2331 ANKERL_NANOBENCH(IGNORE_PADDED_POP)
2332 
2333 LinuxPerformanceCounters::~LinuxPerformanceCounters() {
2334  if (-1 != mFd) {
2335  close(mFd);
2336  }
2337 }
2338 
2339 bool LinuxPerformanceCounters::monitor(perf_sw_ids swId, LinuxPerformanceCounters::Target target) {
2340  return monitor(PERF_TYPE_SOFTWARE, swId, target);
2341 }
2342 
2343 bool LinuxPerformanceCounters::monitor(perf_hw_id hwId, LinuxPerformanceCounters::Target target) {
2344  return monitor(PERF_TYPE_HARDWARE, hwId, target);
2345 }
2346 
2347 // overflow is ok, it's checked
2349 void LinuxPerformanceCounters::updateResults(uint64_t numIters) {
2350  // clear old data
2351  for (auto& id_value : mIdToTarget) {
2352  *id_value.second.targetValue = UINT64_C(0);
2353  }
2354 
2355  if (mHasError) {
2356  return;
2357  }
2358 
2359  mTimeEnabledNanos = mCounters[1] - mCalibratedOverhead[1];
2360  mTimeRunningNanos = mCounters[2] - mCalibratedOverhead[2];
2361 
2362  for (uint64_t i = 0; i < mCounters[0]; ++i) {
2363  auto idx = static_cast<size_t>(3 + i * 2 + 0);
2364  auto id = mCounters[idx + 1U];
2365 
2366  auto it = mIdToTarget.find(id);
2367  if (it != mIdToTarget.end()) {
2368 
2369  auto& tgt = it->second;
2370  *tgt.targetValue = mCounters[idx];
2371  if (tgt.correctMeasuringOverhead) {
2372  if (*tgt.targetValue >= mCalibratedOverhead[idx]) {
2373  *tgt.targetValue -= mCalibratedOverhead[idx];
2374  } else {
2375  *tgt.targetValue = 0U;
2376  }
2377  }
2378  if (tgt.correctLoopOverhead) {
2379  auto correctionVal = mLoopOverhead[idx] * numIters;
2380  if (*tgt.targetValue >= correctionVal) {
2381  *tgt.targetValue -= correctionVal;
2382  } else {
2383  *tgt.targetValue = 0U;
2384  }
2385  }
2386  }
2387  }
2388 }
2389 
2390 bool LinuxPerformanceCounters::monitor(uint32_t type, uint64_t eventid, Target target) {
2391  *target.targetValue = (std::numeric_limits<uint64_t>::max)();
2392  if (mHasError) {
2393  return false;
2394  }
2395 
2396  auto pea = perf_event_attr();
2397  std::memset(&pea, 0, sizeof(perf_event_attr));
2398  pea.type = type;
2399  pea.size = sizeof(perf_event_attr);
2400  pea.config = eventid;
2401  pea.disabled = 1; // start counter as disabled
2402  pea.exclude_kernel = 1;
2403  pea.exclude_hv = 1;
2404 
2405  // NOLINTNEXTLINE(hicpp-signed-bitwise)
2406  pea.read_format = PERF_FORMAT_GROUP | PERF_FORMAT_ID | PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING;
2407 
2408  const int pid = 0; // the current process
2409  const int cpu = -1; // all CPUs
2410 # if defined(PERF_FLAG_FD_CLOEXEC) // since Linux 3.14
2411  const unsigned long flags = PERF_FLAG_FD_CLOEXEC;
2412 # else
2413  const unsigned long flags = 0;
2414 # endif
2415 
2416  auto fd = static_cast<int>(syscall(__NR_perf_event_open, &pea, pid, cpu, mFd, flags));
2417  if (-1 == fd) {
2418  return false;
2419  }
2420  if (-1 == mFd) {
2421  // first call: set to fd, and use this from now on
2422  mFd = fd;
2423  }
2424  uint64_t id = 0;
2425  // NOLINTNEXTLINE(hicpp-signed-bitwise)
2426  if (-1 == ioctl(fd, PERF_EVENT_IOC_ID, &id)) {
2427  // couldn't get id
2428  return false;
2429  }
2430 
2431  // insert into map, rely on the fact that map's references are constant.
2432  mIdToTarget.emplace(id, target);
2433 
2434  // prepare readformat with the correct size (after the insert)
2435  auto size = 3 + 2 * mIdToTarget.size();
2436  mCounters.resize(size);
2437  mCalibratedOverhead.resize(size);
2438  mLoopOverhead.resize(size);
2439 
2440  return true;
2441 }
2442 
2443 PerformanceCounters::PerformanceCounters()
2444  : mPc(new LinuxPerformanceCounters())
2445  , mVal()
2446  , mHas() {
2447 
2448  mHas.pageFaults = mPc->monitor(PERF_COUNT_SW_PAGE_FAULTS, LinuxPerformanceCounters::Target(&mVal.pageFaults, true, false));
2449  mHas.cpuCycles = mPc->monitor(PERF_COUNT_HW_REF_CPU_CYCLES, LinuxPerformanceCounters::Target(&mVal.cpuCycles, true, false));
2450  mHas.contextSwitches =
2451  mPc->monitor(PERF_COUNT_SW_CONTEXT_SWITCHES, LinuxPerformanceCounters::Target(&mVal.contextSwitches, true, false));
2452  mHas.instructions = mPc->monitor(PERF_COUNT_HW_INSTRUCTIONS, LinuxPerformanceCounters::Target(&mVal.instructions, true, true));
2453  mHas.branchInstructions =
2454  mPc->monitor(PERF_COUNT_HW_BRANCH_INSTRUCTIONS, LinuxPerformanceCounters::Target(&mVal.branchInstructions, true, false));
2455  mHas.branchMisses = mPc->monitor(PERF_COUNT_HW_BRANCH_MISSES, LinuxPerformanceCounters::Target(&mVal.branchMisses, true, false));
2456  // mHas.branchMisses = false;
2457 
2458  mPc->start();
2459  mPc->calibrate([] {
2460  auto before = ankerl::nanobench::Clock::now();
2461  auto after = ankerl::nanobench::Clock::now();
2462  (void)before;
2463  (void)after;
2464  });
2465 
2466  if (mPc->hasError()) {
2467  // something failed, don't monitor anything.
2468  mHas = PerfCountSet<bool>{};
2469  }
2470 }
2471 
2472 PerformanceCounters::~PerformanceCounters() {
2473  if (nullptr != mPc) {
2474  delete mPc;
2475  }
2476 }
2477 
2478 void PerformanceCounters::beginMeasure() {
2479  mPc->beginMeasure();
2480 }
2481 
2482 void PerformanceCounters::endMeasure() {
2483  mPc->endMeasure();
2484 }
2485 
2486 void PerformanceCounters::updateResults(uint64_t numIters) {
2487  mPc->updateResults(numIters);
2488 }
2489 
2490 # else
2491 
2492 PerformanceCounters::PerformanceCounters() = default;
2493 PerformanceCounters::~PerformanceCounters() = default;
2494 void PerformanceCounters::beginMeasure() {}
2495 void PerformanceCounters::endMeasure() {}
2496 void PerformanceCounters::updateResults(uint64_t) {}
2497 
2498 # endif
2499 
2500 ANKERL_NANOBENCH(NODISCARD) PerfCountSet<uint64_t> const& PerformanceCounters::val() const noexcept {
2501  return mVal;
2502 }
2503 ANKERL_NANOBENCH(NODISCARD) PerfCountSet<bool> const& PerformanceCounters::has() const noexcept {
2504  return mHas;
2505 }
2506 
2507 // formatting utilities
2508 namespace fmt {
2509 
2510 // adds thousands separator to numbers
2511 NumSep::NumSep(char sep)
2512  : mSep(sep) {}
2513 
2514 char NumSep::do_thousands_sep() const {
2515  return mSep;
2516 }
2517 
2518 std::string NumSep::do_grouping() const {
2519  return "\003";
2520 }
2521 
2522 // RAII to save & restore a stream's state
2523 StreamStateRestorer::StreamStateRestorer(std::ostream& s)
2524  : mStream(s)
2525  , mLocale(s.getloc())
2526  , mPrecision(s.precision())
2527  , mWidth(s.width())
2528  , mFill(s.fill())
2529  , mFmtFlags(s.flags()) {}
2530 
2531 StreamStateRestorer::~StreamStateRestorer() {
2532  restore();
2533 }
2534 
2535 // sets back all stream info that we remembered at construction
2536 void StreamStateRestorer::restore() {
2537  mStream.imbue(mLocale);
2538  mStream.precision(mPrecision);
2539  mStream.width(mWidth);
2540  mStream.fill(mFill);
2541  mStream.flags(mFmtFlags);
2542 }
2543 
2544 Number::Number(int width, int precision, int64_t value)
2545  : mWidth(width)
2546  , mPrecision(precision)
2547  , mValue(static_cast<double>(value)) {}
2548 
2549 Number::Number(int width, int precision, double value)
2550  : mWidth(width)
2551  , mPrecision(precision)
2552  , mValue(value) {}
2553 
2554 std::ostream& Number::write(std::ostream& os) const {
2555  StreamStateRestorer restorer(os);
2556  os.imbue(std::locale(os.getloc(), new NumSep(',')));
2557  os << std::setw(mWidth) << std::setprecision(mPrecision) << std::fixed << mValue;
2558  return os;
2559 }
2560 
2561 std::string Number::to_s() const {
2562  std::stringstream ss;
2563  write(ss);
2564  return ss.str();
2565 }
2566 
2567 std::string to_s(uint64_t n) {
2568  std::string str;
2569  do {
2570  str += static_cast<char>('0' + static_cast<char>(n % 10));
2571  n /= 10;
2572  } while (n != 0);
2573  std::reverse(str.begin(), str.end());
2574  return str;
2575 }
2576 
2577 std::ostream& operator<<(std::ostream& os, Number const& n) {
2578  return n.write(os);
2579 }
2580 
2581 MarkDownColumn::MarkDownColumn(int w, int prec, std::string const& tit, std::string const& suff, double val)
2582  : mWidth(w)
2583  , mPrecision(prec)
2584  , mTitle(tit)
2585  , mSuffix(suff)
2586  , mValue(val) {}
2587 
2588 std::string MarkDownColumn::title() const {
2589  std::stringstream ss;
2590  ss << '|' << std::setw(mWidth - 2) << std::right << mTitle << ' ';
2591  return ss.str();
2592 }
2593 
2594 std::string MarkDownColumn::separator() const {
2595  std::string sep(static_cast<size_t>(mWidth), '-');
2596  sep.front() = '|';
2597  sep.back() = ':';
2598  return sep;
2599 }
2600 
2601 std::string MarkDownColumn::invalid() const {
2602  std::string sep(static_cast<size_t>(mWidth), ' ');
2603  sep.front() = '|';
2604  sep[sep.size() - 2] = '-';
2605  return sep;
2606 }
2607 
2608 std::string MarkDownColumn::value() const {
2609  std::stringstream ss;
2610  auto width = mWidth - 2 - static_cast<int>(mSuffix.size());
2611  ss << '|' << Number(width, mPrecision, mValue) << mSuffix << ' ';
2612  return ss.str();
2613 }
2614 
2615 // Formats any text as markdown code, escaping backticks.
2616 MarkDownCode::MarkDownCode(std::string const& what) {
2617  mWhat.reserve(what.size() + 2);
2618  mWhat.push_back('`');
2619  for (char c : what) {
2620  mWhat.push_back(c);
2621  if ('`' == c) {
2622  mWhat.push_back('`');
2623  }
2624  }
2625  mWhat.push_back('`');
2626 }
2627 
2628 std::ostream& MarkDownCode::write(std::ostream& os) const {
2629  return os << mWhat;
2630 }
2631 
2632 std::ostream& operator<<(std::ostream& os, MarkDownCode const& mdCode) {
2633  return mdCode.write(os);
2634 }
2635 } // namespace fmt
2636 } // namespace detail
2637 
2638 // provide implementation here so it's only generated once
2639 Config::Config() = default;
2640 Config::~Config() = default;
2641 Config& Config::operator=(Config const&) = default;
2642 Config& Config::operator=(Config&&) = default;
2643 Config::Config(Config const&) = default;
2644 Config::Config(Config&&) noexcept = default;
2645 
2646 // provide implementation here so it's only generated once
2647 Result::~Result() = default;
2648 Result& Result::operator=(Result const&) = default;
2649 Result& Result::operator=(Result&&) = default;
2650 Result::Result(Result const&) = default;
2651 Result::Result(Result&&) noexcept = default;
2652 
2653 namespace detail {
2654 template <typename T>
2655 inline constexpr typename std::underlying_type<T>::type u(T val) noexcept {
2656  return static_cast<typename std::underlying_type<T>::type>(val);
2657 }
2658 } // namespace detail
2659 
2660 // Result returned after a benchmark has finished. Can be used as a baseline for relative().
2661 Result::Result(Config const& benchmarkConfig)
2662  : mConfig(benchmarkConfig)
2663  , mNameToMeasurements{detail::u(Result::Measure::_size)} {}
2664 
2665 void Result::add(Clock::duration totalElapsed, uint64_t iters, detail::PerformanceCounters const& pc) {
2666  using detail::d;
2667  using detail::u;
2668 
2669  double dIters = d(iters);
2670  mNameToMeasurements[u(Result::Measure::iterations)].push_back(dIters);
2671 
2672  mNameToMeasurements[u(Result::Measure::elapsed)].push_back(d(totalElapsed) / dIters);
2673  if (pc.has().pageFaults) {
2674  mNameToMeasurements[u(Result::Measure::pagefaults)].push_back(d(pc.val().pageFaults) / dIters);
2675  }
2676  if (pc.has().cpuCycles) {
2677  mNameToMeasurements[u(Result::Measure::cpucycles)].push_back(d(pc.val().cpuCycles) / dIters);
2678  }
2679  if (pc.has().contextSwitches) {
2680  mNameToMeasurements[u(Result::Measure::contextswitches)].push_back(d(pc.val().contextSwitches) / dIters);
2681  }
2682  if (pc.has().instructions) {
2683  mNameToMeasurements[u(Result::Measure::instructions)].push_back(d(pc.val().instructions) / dIters);
2684  }
2685  if (pc.has().branchInstructions) {
2686  double branchInstructions = 0.0;
2687  // correcting branches: remove branch introduced by the while (...) loop for each iteration.
2688  if (pc.val().branchInstructions > iters + 1U) {
2689  branchInstructions = d(pc.val().branchInstructions - (iters + 1U));
2690  }
2691  mNameToMeasurements[u(Result::Measure::branchinstructions)].push_back(branchInstructions / dIters);
2692 
2693  if (pc.has().branchMisses) {
2694  // correcting branch misses
2695  double branchMisses = d(pc.val().branchMisses);
2696  if (branchMisses > branchInstructions) {
2697  // can't have branch misses when there were branches...
2698  branchMisses = branchInstructions;
2699  }
2700 
2701  // assuming at least one missed branch for the loop
2702  branchMisses -= 1.0;
2703  if (branchMisses < 1.0) {
2704  branchMisses = 1.0;
2705  }
2706  mNameToMeasurements[u(Result::Measure::branchmisses)].push_back(branchMisses / dIters);
2707  }
2708  }
2709 }
2710 
2711 Config const& Result::config() const noexcept {
2712  return mConfig;
2713 }
2714 
2715 inline double calcMedian(std::vector<double>& data) {
2716  if (data.empty()) {
2717  return 0.0;
2718  }
2719  std::sort(data.begin(), data.end());
2720 
2721  auto midIdx = data.size() / 2U;
2722  if (1U == (data.size() & 1U)) {
2723  return data[midIdx];
2724  }
2725  return (data[midIdx - 1U] + data[midIdx]) / 2U;
2726 }
2727 
2728 double Result::median(Measure m) const {
2729  // create a copy so we can sort
2730  auto data = mNameToMeasurements[detail::u(m)];
2731  return calcMedian(data);
2732 }
2733 
2734 double Result::average(Measure m) const {
2735  using detail::d;
2736  auto const& data = mNameToMeasurements[detail::u(m)];
2737  if (data.empty()) {
2738  return 0.0;
2739  }
2740 
2741  // create a copy so we can sort
2742  return sum(m) / d(data.size());
2743 }
2744 
2745 double Result::medianAbsolutePercentError(Measure m) const {
2746  // create copy
2747  auto data = mNameToMeasurements[detail::u(m)];
2748 
2749  // calculates MdAPE which is the median of percentage error
2750  // see https://www.spiderfinancial.com/support/documentation/numxl/reference-manual/forecasting-performance/mdape
2751  auto med = calcMedian(data);
2752 
2753  // transform the data to absolute error
2754  for (auto& x : data) {
2755  x = (x - med) / x;
2756  if (x < 0) {
2757  x = -x;
2758  }
2759  }
2760  return calcMedian(data);
2761 }
2762 
2763 double Result::sum(Measure m) const noexcept {
2764  auto const& data = mNameToMeasurements[detail::u(m)];
2765  return std::accumulate(data.begin(), data.end(), 0.0);
2766 }
2767 
2768 double Result::sumProduct(Measure m1, Measure m2) const noexcept {
2769  auto const& data1 = mNameToMeasurements[detail::u(m1)];
2770  auto const& data2 = mNameToMeasurements[detail::u(m2)];
2771 
2772  if (data1.size() != data2.size()) {
2773  return 0.0;
2774  }
2775 
2776  double result = 0.0;
2777  for (size_t i = 0, s = data1.size(); i != s; ++i) {
2778  result += data1[i] * data2[i];
2779  }
2780  return result;
2781 }
2782 
2783 bool Result::has(Measure m) const noexcept {
2784  return !mNameToMeasurements[detail::u(m)].empty();
2785 }
2786 
2787 double Result::get(size_t idx, Measure m) const {
2788  auto const& data = mNameToMeasurements[detail::u(m)];
2789  return data.at(idx);
2790 }
2791 
2792 bool Result::empty() const noexcept {
2793  return 0U == size();
2794 }
2795 
2796 size_t Result::size() const noexcept {
2797  auto const& data = mNameToMeasurements[detail::u(Measure::elapsed)];
2798  return data.size();
2799 }
2800 
2801 double Result::minimum(Measure m) const noexcept {
2802  auto const& data = mNameToMeasurements[detail::u(m)];
2803  if (data.empty()) {
2804  return 0.0;
2805  }
2806 
2807  // here its save to assume that at least one element is there
2808  return *std::min_element(data.begin(), data.end());
2809 }
2810 
2811 double Result::maximum(Measure m) const noexcept {
2812  auto const& data = mNameToMeasurements[detail::u(m)];
2813  if (data.empty()) {
2814  return 0.0;
2815  }
2816 
2817  // here its save to assume that at least one element is there
2818  return *std::max_element(data.begin(), data.end());
2819 }
2820 
2821 Result::Measure Result::fromString(std::string const& str) {
2822  if (str == "elapsed") {
2823  return Measure::elapsed;
2824  } else if (str == "iterations") {
2825  return Measure::iterations;
2826  } else if (str == "pagefaults") {
2827  return Measure::pagefaults;
2828  } else if (str == "cpucycles") {
2829  return Measure::cpucycles;
2830  } else if (str == "contextswitches") {
2831  return Measure::contextswitches;
2832  } else if (str == "instructions") {
2833  return Measure::instructions;
2834  } else if (str == "branchinstructions") {
2835  return Measure::branchinstructions;
2836  } else if (str == "branchmisses") {
2837  return Measure::branchmisses;
2838  } else {
2839  // not found, return _size
2840  return Measure::_size;
2841  }
2842 }
2843 
2844 // Configuration of a microbenchmark.
2845 Bench::Bench() {
2846  mConfig.mOut = &std::cout;
2847 }
2848 
2849 Bench::Bench(Bench&&) = default;
2850 Bench& Bench::operator=(Bench&&) = default;
2851 Bench::Bench(Bench const&) = default;
2852 Bench& Bench::operator=(Bench const&) = default;
2853 Bench::~Bench() noexcept = default;
2854 
2855 double Bench::batch() const noexcept {
2856  return mConfig.mBatch;
2857 }
2858 
2859 double Bench::complexityN() const noexcept {
2860  return mConfig.mComplexityN;
2861 }
2862 
2863 // 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%
2864 // means it is slower than the baseline.
2865 Bench& Bench::relative(bool isRelativeEnabled) noexcept {
2866  mConfig.mIsRelative = isRelativeEnabled;
2867  return *this;
2868 }
2869 bool Bench::relative() const noexcept {
2870  return mConfig.mIsRelative;
2871 }
2872 
2873 Bench& Bench::performanceCounters(bool showPerformanceCounters) noexcept {
2874  mConfig.mShowPerformanceCounters = showPerformanceCounters;
2875  return *this;
2876 }
2877 bool Bench::performanceCounters() const noexcept {
2878  return mConfig.mShowPerformanceCounters;
2879 }
2880 
2881 // Operation unit. Defaults to "op", could be e.g. "byte" for string processing.
2882 // If u differs from currently set unit, the stored results will be cleared.
2883 // Use singular (byte, not bytes).
2884 Bench& Bench::unit(char const* u) {
2885  if (u != mConfig.mUnit) {
2886  mResults.clear();
2887  }
2888  mConfig.mUnit = u;
2889  return *this;
2890 }
2891 
2892 Bench& Bench::unit(std::string const& u) {
2893  return unit(u.c_str());
2894 }
2895 
2896 std::string const& Bench::unit() const noexcept {
2897  return mConfig.mUnit;
2898 }
2899 
2900 // If benchmarkTitle differs from currently set title, the stored results will be cleared.
2901 Bench& Bench::title(const char* benchmarkTitle) {
2902  if (benchmarkTitle != mConfig.mBenchmarkTitle) {
2903  mResults.clear();
2904  }
2905  mConfig.mBenchmarkTitle = benchmarkTitle;
2906  return *this;
2907 }
2908 Bench& Bench::title(std::string const& benchmarkTitle) {
2909  if (benchmarkTitle != mConfig.mBenchmarkTitle) {
2910  mResults.clear();
2911  }
2912  mConfig.mBenchmarkTitle = benchmarkTitle;
2913  return *this;
2914 }
2915 
2916 std::string const& Bench::title() const noexcept {
2917  return mConfig.mBenchmarkTitle;
2918 }
2919 
2920 Bench& Bench::name(const char* benchmarkName) {
2921  mConfig.mBenchmarkName = benchmarkName;
2922  return *this;
2923 }
2924 
2925 Bench& Bench::name(std::string const& benchmarkName) {
2926  mConfig.mBenchmarkName = benchmarkName;
2927  return *this;
2928 }
2929 
2930 std::string const& Bench::name() const noexcept {
2931  return mConfig.mBenchmarkName;
2932 }
2933 
2934 // Number of epochs to evaluate. The reported result will be the median of evaluation of each epoch.
2935 Bench& Bench::epochs(size_t numEpochs) noexcept {
2936  mConfig.mNumEpochs = numEpochs;
2937  return *this;
2938 }
2939 size_t Bench::epochs() const noexcept {
2940  return mConfig.mNumEpochs;
2941 }
2942 
2943 // Desired evaluation time is a multiple of clock resolution. Default is to be 1000 times above this measurement precision.
2944 Bench& Bench::clockResolutionMultiple(size_t multiple) noexcept {
2945  mConfig.mClockResolutionMultiple = multiple;
2946  return *this;
2947 }
2948 size_t Bench::clockResolutionMultiple() const noexcept {
2949  return mConfig.mClockResolutionMultiple;
2950 }
2951 
2952 // Sets the maximum time each epoch should take. Default is 100ms.
2953 Bench& Bench::maxEpochTime(std::chrono::nanoseconds t) noexcept {
2954  mConfig.mMaxEpochTime = t;
2955  return *this;
2956 }
2957 std::chrono::nanoseconds Bench::maxEpochTime() const noexcept {
2958  return mConfig.mMaxEpochTime;
2959 }
2960 
2961 // Sets the maximum time each epoch should take. Default is 100ms.
2962 Bench& Bench::minEpochTime(std::chrono::nanoseconds t) noexcept {
2963  mConfig.mMinEpochTime = t;
2964  return *this;
2965 }
2966 std::chrono::nanoseconds Bench::minEpochTime() const noexcept {
2967  return mConfig.mMinEpochTime;
2968 }
2969 
2970 Bench& Bench::minEpochIterations(uint64_t numIters) noexcept {
2971  mConfig.mMinEpochIterations = (numIters == 0) ? 1 : numIters;
2972  return *this;
2973 }
2974 uint64_t Bench::minEpochIterations() const noexcept {
2975  return mConfig.mMinEpochIterations;
2976 }
2977 
2978 Bench& Bench::epochIterations(uint64_t numIters) noexcept {
2979  mConfig.mEpochIterations = numIters;
2980  return *this;
2981 }
2982 uint64_t Bench::epochIterations() const noexcept {
2983  return mConfig.mEpochIterations;
2984 }
2985 
2986 Bench& Bench::warmup(uint64_t numWarmupIters) noexcept {
2987  mConfig.mWarmup = numWarmupIters;
2988  return *this;
2989 }
2990 uint64_t Bench::warmup() const noexcept {
2991  return mConfig.mWarmup;
2992 }
2993 
2994 Bench& Bench::config(Config const& benchmarkConfig) {
2995  mConfig = benchmarkConfig;
2996  return *this;
2997 }
2998 Config const& Bench::config() const noexcept {
2999  return mConfig;
3000 }
3001 
3002 Bench& Bench::output(std::ostream* outstream) noexcept {
3003  mConfig.mOut = outstream;
3004  return *this;
3005 }
3006 
3007 ANKERL_NANOBENCH(NODISCARD) std::ostream* Bench::output() const noexcept {
3008  return mConfig.mOut;
3009 }
3010 
3011 std::vector<Result> const& Bench::results() const noexcept {
3012  return mResults;
3013 }
3014 
3015 Bench& Bench::render(char const* templateContent, std::ostream& os) {
3016  ::ankerl::nanobench::render(templateContent, *this, os);
3017  return *this;
3018 }
3019 
3020 std::vector<BigO> Bench::complexityBigO() const {
3021  std::vector<BigO> bigOs;
3022  auto rangeMeasure = BigO::collectRangeMeasure(mResults);
3023  bigOs.emplace_back("O(1)", rangeMeasure, [](double) {
3024  return 1.0;
3025  });
3026  bigOs.emplace_back("O(n)", rangeMeasure, [](double n) {
3027  return n;
3028  });
3029  bigOs.emplace_back("O(log n)", rangeMeasure, [](double n) {
3030  return std::log2(n);
3031  });
3032  bigOs.emplace_back("O(n log n)", rangeMeasure, [](double n) {
3033  return n * std::log2(n);
3034  });
3035  bigOs.emplace_back("O(n^2)", rangeMeasure, [](double n) {
3036  return n * n;
3037  });
3038  bigOs.emplace_back("O(n^3)", rangeMeasure, [](double n) {
3039  return n * n * n;
3040  });
3041  std::sort(bigOs.begin(), bigOs.end());
3042  return bigOs;
3043 }
3044 
3045 Rng::Rng()
3046  : mX(0)
3047  , mY(0) {
3048  std::random_device rd;
3049  std::uniform_int_distribution<uint64_t> dist;
3050  do {
3051  mX = dist(rd);
3052  mY = dist(rd);
3053  } while (mX == 0 && mY == 0);
3054 }
3055 
3057 uint64_t splitMix64(uint64_t& state) noexcept {
3058  uint64_t z = (state += UINT64_C(0x9e3779b97f4a7c15));
3059  z = (z ^ (z >> 30U)) * UINT64_C(0xbf58476d1ce4e5b9);
3060  z = (z ^ (z >> 27U)) * UINT64_C(0x94d049bb133111eb);
3061  return z ^ (z >> 31U);
3062 }
3063 
3064 // Seeded as described in romu paper (update april 2020)
3065 Rng::Rng(uint64_t seed) noexcept
3066  : mX(splitMix64(seed))
3067  , mY(splitMix64(seed)) {
3068  for (size_t i = 0; i < 10; ++i) {
3069  operator()();
3070  }
3071 }
3072 
3073 // only internally used to copy the RNG.
3074 Rng::Rng(uint64_t x, uint64_t y) noexcept
3075  : mX(x)
3076  , mY(y) {}
3077 
3078 Rng Rng::copy() const noexcept {
3079  return Rng{mX, mY};
3080 }
3081 
3082 BigO::RangeMeasure BigO::collectRangeMeasure(std::vector<Result> const& results) {
3083  BigO::RangeMeasure rangeMeasure;
3084  for (auto const& result : results) {
3085  if (result.config().mComplexityN > 0.0) {
3086  rangeMeasure.emplace_back(result.config().mComplexityN, result.median(Result::Measure::elapsed));
3087  }
3088  }
3089  return rangeMeasure;
3090 }
3091 
3092 BigO::BigO(std::string const& bigOName, RangeMeasure const& rangeMeasure)
3093  : mName(bigOName) {
3094 
3095  // estimate the constant factor
3096  double sumRangeMeasure = 0.0;
3097  double sumRangeRange = 0.0;
3098 
3099  for (size_t i = 0; i < rangeMeasure.size(); ++i) {
3100  sumRangeMeasure += rangeMeasure[i].first * rangeMeasure[i].second;
3101  sumRangeRange += rangeMeasure[i].first * rangeMeasure[i].first;
3102  }
3103  mConstant = sumRangeMeasure / sumRangeRange;
3104 
3105  // calculate root mean square
3106  double err = 0.0;
3107  double sumMeasure = 0.0;
3108  for (size_t i = 0; i < rangeMeasure.size(); ++i) {
3109  auto diff = mConstant * rangeMeasure[i].first - rangeMeasure[i].second;
3110  err += diff * diff;
3111 
3112  sumMeasure += rangeMeasure[i].second;
3113  }
3114 
3115  auto n = static_cast<double>(rangeMeasure.size());
3116  auto mean = sumMeasure / n;
3117  mNormalizedRootMeanSquare = std::sqrt(err / n) / mean;
3118 }
3119 
3120 BigO::BigO(const char* bigOName, RangeMeasure const& rangeMeasure)
3121  : BigO(std::string(bigOName), rangeMeasure) {}
3122 
3123 std::string const& BigO::name() const noexcept {
3124  return mName;
3125 }
3126 
3127 double BigO::constant() const noexcept {
3128  return mConstant;
3129 }
3130 
3131 double BigO::normalizedRootMeanSquare() const noexcept {
3132  return mNormalizedRootMeanSquare;
3133 }
3134 
3135 bool BigO::operator<(BigO const& other) const noexcept {
3136  return std::tie(mNormalizedRootMeanSquare, mName) < std::tie(other.mNormalizedRootMeanSquare, other.mName);
3137 }
3138 
3139 std::ostream& operator<<(std::ostream& os, BigO const& bigO) {
3140  return os << bigO.constant() << " * " << bigO.name() << ", rms=" << bigO.normalizedRootMeanSquare();
3141 }
3142 
3143 std::ostream& operator<<(std::ostream& os, std::vector<ankerl::nanobench::BigO> const& bigOs) {
3144  detail::fmt::StreamStateRestorer restorer(os);
3145  os << std::endl << "| coefficient | err% | complexity" << std::endl << "|--------------:|-------:|------------" << std::endl;
3146  for (auto const& bigO : bigOs) {
3147  os << "|" << std::setw(14) << std::setprecision(7) << std::scientific << bigO.constant() << " ";
3148  os << "|" << detail::fmt::Number(6, 1, bigO.normalizedRootMeanSquare() * 100.0) << "% ";
3149  os << "| " << bigO.name();
3150  os << std::endl;
3151  }
3152  return os;
3153 }
3154 
3155 } // namespace nanobench
3156 } // namespace ankerl
3157 
3158 #endif // ANKERL_NANOBENCH_IMPLEMENT
3159 #endif // ANKERL_NANOBENCH_H_INCLUDED
3160 
char const * json() noexcept
Template to generate JSON data.
void moveResultTo(std::vector< Result > &results) noexcept
#define ANKERL_NANOBENCH_LOG(x)
Definition: nanobench.h:83
std::deque< CInv >::iterator it
const std::chrono::seconds now
std::vector< std::pair< double, double >> RangeMeasure
Definition: nanobench.h:1019
bool operator==(const CNetAddr &a, const CNetAddr &b)
Definition: netaddress.cpp:585
static RangeMeasure collectRangeMeasure(std::vector< Result > const &results)
void add(std::chrono::nanoseconds elapsed, PerformanceCounters const &pc) noexcept
fs::ifstream ifstream
Definition: fs.h:90
void render(char const *mustacheTemplate, Bench const &bench, std::ostream &out)
Renders output from a mustache-like template and benchmark results.
double uniform01() noexcept
Provides a random uniform double value between 0 and 1.
Definition: nanobench.h:1087
char const * htmlBoxplot() noexcept
HTML output that uses plotly to generate an interactive boxplot chart. See the tutorial for an exampl...
An extremely fast random generator.
Definition: nanobench.h:453
State
The various states a (txhash,peer) pair can be in.
Definition: txrequest.cpp:39
std::ostream & operator<<(std::ostream &os, BigO const &bigO)
std::enable_if<!doNotOptimizeNeedsIndirect< T >)>::type doNotOptimizeAway(T const &val)
Definition: nanobench.h:956
#define ANKERL_NANOBENCH_NO_SANITIZE(...)
Definition: nanobench.h:95
volatile double sum
Definition: examples.cpp:10
Bench & run(char const *benchmarkName, Op &&op)
Repeatedly calls op() based on the configuration, and performs measurements.
Definition: nanobench.h:1134
#define NODISCARD
Definition: attributes.h:18
const char * name
Definition: rest.cpp:41
BigO(std::string const &bigOName, RangeMeasure const &rangeMeasure, Op rangeToN)
Definition: nanobench.h:1036
void doNotOptimizeAway(Arg &&arg)
Makes sure none of the given arguments are optimized away by the compiler.
Definition: nanobench.h:1179
Bench & complexityN(T b) noexcept
Definition: nanobench.h:1165
static constexpr uint64_t rotl(uint64_t x, unsigned k) noexcept
Definition: nanobench.h:1106
std::conditional< std::chrono::high_resolution_clock::is_steady, std::chrono::high_resolution_clock, std::chrono::steady_clock >::type Clock
Definition: nanobench.h:118
static Measure fromString(std::string const &str)
#define ANKERL_NANOBENCH(x)
Definition: nanobench.h:48
static RPCHelpMan stop()
Definition: server.cpp:155
constexpr bool doNotOptimizeNeedsIndirect()
Definition: nanobench.h:950
char const * csv() noexcept
CSV data for the benchmark results.
void shuffle(Container &container) noexcept
Shuffles all entries in the given container.
Definition: nanobench.h:1097
int flags
Definition: bitcoin-tx.cpp:506
bool operator<(const CNetAddr &a, const CNetAddr &b)
Definition: netaddress.cpp:590
ANKERL_NANOBENCH(NODISCARD) std Bench & doNotOptimizeAway(Arg &&arg)
Retrieves all benchmark results collected by the bench object so far.
void * memcpy(void *a, const void *b, size_t c)
static constexpr uint64_t() max()
BigO(char const *bigOName, RangeMeasure const &rangeMeasure, Op rangeToN)
Definition: nanobench.h:1032
uint64_t result_type
This RNG provides 64bit randomness.
Definition: nanobench.h:458
static int count
Definition: tests.c:35
Main entry point to nanobench&#39;s benchmarking facility.
Definition: nanobench.h:583
std::vector< BigO > complexityBigO() const
ANKERL_NANOBENCH(NODISCARD) std Bench & batch(T b) noexcept
Sets the batch size.
PerformanceCounters & performanceCounters()
static constexpr uint64_t() min()
static RangeMeasure mapRangeMeasure(RangeMeasure data, Op op)
Definition: nanobench.h:1022
#define ANKERL_NANOBENCH_IS_TRIVIALLY_COPYABLE(...)
Definition: nanobench.h:109