30 #ifndef ANKERL_NANOBENCH_H_INCLUDED
31 #define ANKERL_NANOBENCH_H_INCLUDED
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
48 #define ANKERL_NANOBENCH(x) ANKERL_NANOBENCH_PRIVATE_##x()
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
56 #if ANKERL_NANOBENCH(CXX) >= ANKERL_NANOBENCH(CXX17)
57 # define ANKERL_NANOBENCH_PRIVATE_NODISCARD() [[nodiscard]]
59 # define ANKERL_NANOBENCH_PRIVATE_NODISCARD()
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")
67 # define ANKERL_NANOBENCH_PRIVATE_IGNORE_PADDED_PUSH()
68 # define ANKERL_NANOBENCH_PRIVATE_IGNORE_PADDED_POP()
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")
75 # define ANKERL_NANOBENCH_PRIVATE_IGNORE_EFFCPP_PUSH()
76 # define ANKERL_NANOBENCH_PRIVATE_IGNORE_EFFCPP_POP()
79 #if defined(ANKERL_NANOBENCH_LOG_ENABLED)
81 # define ANKERL_NANOBENCH_LOG(x) std::cout << __FUNCTION__ << "@" << __LINE__ << ": " << x << std::endl
83 # define ANKERL_NANOBENCH_LOG(x)
86 #if defined(__linux__) && !defined(ANKERL_NANOBENCH_DISABLE_PERF_COUNTERS)
87 # define ANKERL_NANOBENCH_PRIVATE_PERF_COUNTERS() 1
89 # define ANKERL_NANOBENCH_PRIVATE_PERF_COUNTERS() 0
92 #if defined(__clang__)
93 # define ANKERL_NANOBENCH_NO_SANITIZE(...) __attribute__((no_sanitize(__VA_ARGS__)))
95 # define ANKERL_NANOBENCH_NO_SANITIZE(...)
99 # define ANKERL_NANOBENCH_PRIVATE_NOINLINE() __declspec(noinline)
101 # define ANKERL_NANOBENCH_PRIVATE_NOINLINE() __attribute__((noinline))
106 #if defined(__GNUC__) && __GNUC__ < 5
107 # define ANKERL_NANOBENCH_IS_TRIVIALLY_COPYABLE(...) __has_trivial_copy(__VA_ARGS__)
109 # define ANKERL_NANOBENCH_IS_TRIVIALLY_COPYABLE(...) std::is_trivially_copyable<__VA_ARGS__>::value
115 namespace nanobench {
117 using Clock = std::conditional<std::chrono::high_resolution_clock::is_steady, std::chrono::high_resolution_clock,
118 std::chrono::steady_clock>::type;
271 void render(
char const* mustacheTemplate,
Bench const& bench, std::ostream& out);
281 void render(
char const* mustacheTemplate, std::vector<Result>
const& results, std::ostream& out);
284 namespace templates {
295 char const*
csv() noexcept;
318 char const*
json() noexcept;
324 template <
typename T>
330 #if ANKERL_NANOBENCH(PERF_COUNTERS)
331 class LinuxPerformanceCounters;
341 namespace nanobench {
344 template <
typename T>
345 struct PerfCountSet {
359 std::string mBenchmarkTitle =
"benchmark";
360 std::string mBenchmarkName =
"noname";
361 std::string mUnit =
"op";
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};
370 uint64_t mWarmup = 0;
371 std::ostream* mOut =
nullptr;
372 bool mShowPerformanceCounters =
true;
373 bool mIsRelative =
false;
377 Config& operator=(Config
const&);
378 Config& operator=(Config&&);
379 Config(Config
const&);
380 Config(Config&&) noexcept;
400 explicit Result(Config
const& benchmarkConfig);
403 Result& operator=(Result
const&);
404 Result& operator=(Result&&);
406 Result(Result&&) noexcept;
410 void add(
Clock::duration totalElapsed, uint64_t iters, detail::PerformanceCounters const& pc);
428 static
Measure fromString(std::
string const& str);
432 std::vector<std::vector<double>> mNameToMeasurements{};
460 static constexpr uint64_t(min)();
461 static constexpr uint64_t(max)();
473 Rng& operator=(
Rng const&) =
delete;
476 Rng(
Rng&&) noexcept = default;
477 Rng& operator=(
Rng&&) noexcept = default;
478 ~
Rng() noexcept = default;
505 explicit
Rng(uint64_t seed) noexcept;
506 Rng(uint64_t x, uint64_t y) noexcept;
520 inline uint64_t operator()() noexcept;
538 inline uint32_t bounded(uint32_t range) noexcept;
549 inline
double uniform01() noexcept;
558 template <typename Container>
559 void shuffle(Container& container) noexcept;
562 static constexpr uint64_t rotl(uint64_t x,
unsigned k) noexcept;
590 Bench(Bench&& other);
591 Bench& operator=(Bench&& other);
592 Bench(Bench
const& other);
593 Bench& operator=(Bench
const& other);
614 template <
typename Op>
616 Bench& run(
char const* benchmarkName, Op&& op);
618 template <
typename Op>
620 Bench& run(std::string
const& benchmarkName, Op&& op);
626 template <
typename Op>
635 Bench& title(
char const* benchmarkTitle);
636 Bench& title(std::string
const& benchmarkTitle);
640 Bench&
name(
char const* benchmarkName);
641 Bench&
name(std::string
const& benchmarkName);
653 template <
typename T>
654 Bench& batch(T b) noexcept;
665 Bench& unit(
char const* unit);
666 Bench& unit(std::string
const& unit);
676 Bench& output(std::ostream* outstream) noexcept;
699 Bench& clockResolutionMultiple(
size_t multiple) noexcept;
717 Bench& epochs(
size_t numEpochs) noexcept;
730 Bench& maxEpochTime(std::chrono::nanoseconds t) noexcept;
743 Bench& minEpochTime(std::chrono::nanoseconds t) noexcept;
756 Bench& minEpochIterations(uint64_t numIters) noexcept;
765 Bench& epochIterations(uint64_t numIters) noexcept;
777 Bench& warmup(uint64_t numWarmupIters) noexcept;
797 Bench& relative(
bool isRelativeEnabled) noexcept;
828 template <
typename Arg>
845 template <
typename T>
846 Bench& complexityN(T b) noexcept;
880 std::vector<BigO> complexityBigO()
const;
905 template <
typename Op>
906 BigO complexityBigO(
char const* name, Op op)
const;
908 template <
typename Op>
909 BigO complexityBigO(std::string
const& name, Op op)
const;
918 Bench&
render(
char const* templateContent, std::ostream& os);
920 Bench& config(Config
const& benchmarkConfig);
925 std::vector<Result> mResults{};
935 template <typename Arg>
940 #if defined(_MSC_VER)
941 void doNotOptimizeAwaySink(
void const*);
943 template <
typename T>
949 template <
typename T>
951 using Decayed =
typename std::decay<T>::type;
955 template <
typename T>
956 typename std::enable_if<!doNotOptimizeNeedsIndirect<T>()>::type
doNotOptimizeAway(T
const& val) {
958 asm volatile(
"" ::
"r"(val));
961 template <
typename T>
962 typename std::enable_if<doNotOptimizeNeedsIndirect<T>()>::type
doNotOptimizeAway(T
const& val) {
964 asm volatile(
"" ::
"m"(val) :
"memory");
974 explicit IterationLogic(
Bench const& config) noexcept;
979 void moveResultTo(std::vector<Result>& results) noexcept;
990 PerformanceCounters(PerformanceCounters
const&) =
delete;
991 PerformanceCounters& operator=(PerformanceCounters
const&) =
delete;
993 PerformanceCounters();
994 ~PerformanceCounters();
998 void updateResults(uint64_t numIters);
1004 #if ANKERL_NANOBENCH(PERF_COUNTERS)
1005 LinuxPerformanceCounters* mPc =
nullptr;
1021 template <
typename Op>
1023 for (
auto& rangeMeasure : data) {
1024 rangeMeasure.first = op(rangeMeasure.first);
1029 static RangeMeasure collectRangeMeasure(std::vector<Result>
const& results);
1031 template <
typename Op>
1033 : BigO(bigOName, mapRangeMeasure(rangeMeasure, rangeToN)) {}
1035 template <
typename Op>
1037 : BigO(bigOName, mapRangeMeasure(rangeMeasure, rangeToN)) {}
1039 BigO(
char const* bigOName, RangeMeasure
const& scaledRangeMeasure);
1040 BigO(std::string
const& bigOName, RangeMeasure
const& scaledRangeMeasure);
1047 std::
string mName{};
1049 double mNormalizedRootMeanSquare{};
1051 std::ostream&
operator<<(std::ostream& os, BigO
const& bigO);
1052 std::ostream& operator<<(std::ostream& os, std::vector<ankerl::nanobench::BigO>
const& bigOs);
1060 namespace nanobench {
1067 return (std::numeric_limits<uint64_t>::max)();
1071 uint64_t
Rng::operator()() noexcept {
1074 mX = UINT64_C(15241094284759029579) * mY;
1075 mY = rotl(mY - x, 27);
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);
1088 auto i = (UINT64_C(0x3ff) << 52U) | (
operator()() >> 12U);
1096 template <
typename Container>
1098 auto size =
static_cast<uint32_t
>(container.size());
1099 for (
auto i = size; i > 1U; --i) {
1101 auto p = bounded(i);
1102 swap(container[i - 1], container[p]);
1106 constexpr uint64_t
Rng::rotl(uint64_t x,
unsigned k) noexcept {
1107 return (x << k) | (x >> (64U - k));
1110 template <
typename Op>
1117 while (
auto n = iterationLogic.numIters()) {
1125 pc.updateResults(iterationLogic.numIters());
1126 iterationLogic.
add(after - before, pc);
1133 template <
typename Op>
1135 name(benchmarkName);
1136 return run(std::forward<Op>(op));
1139 template <
typename Op>
1141 name(benchmarkName);
1142 return run(std::forward<Op>(op));
1145 template <
typename Op>
1150 template <
typename Op>
1157 template <
typename T>
1159 mConfig.mBatch =
static_cast<double>(b);
1164 template <
typename T>
1166 mConfig.mComplexityN =
static_cast<double>(n);
1171 template <
typename Arg>
1178 template <
typename Arg>
1185 #if defined(_MSC_VER)
1186 template <
typename T>
1188 doNotOptimizeAwaySink(&val);
1197 #if defined(ANKERL_NANOBENCH_IMPLEMENT)
1203 # include <algorithm>
1209 # include <iostream>
1213 # include <stdexcept>
1215 # if defined(__linux__)
1216 # include <unistd.h>
1218 # if ANKERL_NANOBENCH(PERF_COUNTERS)
1221 # include <linux/perf_event.h>
1222 # include <sys/ioctl.h>
1223 # include <sys/syscall.h>
1224 # include <unistd.h>
1230 namespace nanobench {
1241 class StreamStateRestorer;
1243 class MarkDownColumn;
1254 namespace nanobench {
1256 uint64_t splitMix64(uint64_t& state) noexcept;
1261 template <
typename T>
1262 inline double d(T t) noexcept {
1263 return static_cast<double>(t);
1265 inline double d(Clock::duration duration) noexcept {
1266 return std::chrono::duration_cast<std::chrono::duration<double>>(duration).
count();
1270 inline Clock::duration clockResolution() noexcept;
1274 namespace templates {
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";
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";
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";
1290 enum class Type { tag, content, section, inverted_section };
1294 std::vector<Node> children;
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);
1305 static std::vector<Node> parseMustacheTemplate(
char const** tpl) {
1306 std::vector<Node> nodes;
1309 auto begin = std::strstr(*tpl,
"{{");
1311 if (begin !=
nullptr) {
1313 end = std::strstr(begin,
"}}");
1316 if (begin ==
nullptr || end ==
nullptr) {
1318 nodes.emplace_back(Node{*tpl, *tpl + std::strlen(*tpl), std::vector<Node>{}, Node::Type::content});
1322 nodes.emplace_back(Node{*tpl, begin - 2, std::vector<Node>{}, Node::Type::content});
1332 nodes.emplace_back(Node{begin + 1, end, parseMustacheTemplate(tpl), Node::Type::section});
1336 nodes.emplace_back(Node{begin + 1, end, parseMustacheTemplate(tpl), Node::Type::inverted_section});
1340 nodes.emplace_back(Node{begin, end, std::vector<Node>{}, Node::Type::tag});
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) {
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);
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));
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) {
1378 matchResult.emplace_back(str.substr(0, idxOpen));
1381 matchResult.emplace_back(std::string{});
1382 for (
size_t i = idxOpen + 1; i != idxClose; ++i) {
1383 if (str[i] ==
' ' || str[i] ==
'\t') {
1387 if (str[i] ==
',') {
1389 matchResult.emplace_back(std::string{});
1393 matchResult.back() += str[i];
1398 static bool generateConfigTag(Node
const& n, Config
const& config, std::ostream& out) {
1402 out << config.mBenchmarkTitle;
1404 }
else if (n ==
"name") {
1405 out << config.mBenchmarkName;
1407 }
else if (n ==
"unit") {
1408 out << config.mUnit;
1410 }
else if (n ==
"batch") {
1411 out << config.mBatch;
1413 }
else if (n ==
"complexityN") {
1414 out << config.mComplexityN;
1416 }
else if (n ==
"epochs") {
1417 out << config.mNumEpochs;
1419 }
else if (n ==
"clockResolution") {
1420 out << d(detail::clockResolution());
1422 }
else if (n ==
"clockResolutionMultiple") {
1423 out << config.mClockResolutionMultiple;
1425 }
else if (n ==
"maxEpochTime") {
1426 out << d(config.mMaxEpochTime);
1428 }
else if (n ==
"minEpochTime") {
1429 out << d(config.mMinEpochTime);
1431 }
else if (n ==
"minEpochIterations") {
1432 out << config.mMinEpochIterations;
1434 }
else if (n ==
"epochIterations") {
1435 out << config.mEpochIterations;
1437 }
else if (n ==
"warmup") {
1438 out << config.mWarmup;
1440 }
else if (n ==
"relative") {
1441 out << config.mIsRelative;
1447 static std::ostream& generateResultTag(Node
const& n,
Result const& r, std::ostream& out) {
1448 if (generateConfigTag(n, r.config(), out)) {
1456 std::vector<std::string> matchResult;
1457 if (matchCmdArgs(std::string(n.begin, n.end), matchResult)) {
1458 if (matchResult.size() == 2) {
1464 if (matchResult[0] ==
"median") {
1465 return out << r.median(m);
1467 if (matchResult[0] ==
"average") {
1468 return out << r.average(m);
1470 if (matchResult[0] ==
"medianAbsolutePercentError") {
1471 return out << r.medianAbsolutePercentError(m);
1473 if (matchResult[0] ==
"sum") {
1474 return out << r.sum(m);
1476 if (matchResult[0] ==
"minimum") {
1477 return out << r.minimum(m);
1479 if (matchResult[0] ==
"maximum") {
1480 return out << r.maximum(m);
1482 }
else if (matchResult.size() == 3) {
1489 if (matchResult[0] ==
"sumProduct") {
1490 return out << r.sumProduct(m1, m2);
1499 throw std::runtime_error(
"command '" + std::string(n.begin, n.end) +
"' not understood");
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)) {
1507 case Node::Type::content:
1508 out.write(n.begin, std::distance(n.begin, n.end));
1511 case Node::Type::inverted_section:
1512 throw std::runtime_error(
"got a inverted section inside measurement");
1514 case Node::Type::section:
1515 throw std::runtime_error(
"got a section inside measurement");
1517 case Node::Type::tag: {
1522 out << r.get(idx, m);
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)) {
1537 case Node::Type::content:
1538 out.write(n.begin, std::distance(n.begin, n.end));
1541 case Node::Type::inverted_section:
1542 throw std::runtime_error(
"got a inverted section inside result");
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);
1550 throw std::runtime_error(
"got a section inside result");
1554 case Node::Type::tag:
1555 generateResultTag(n, r, out);
1567 char const* getEnv(
char const*
name);
1568 bool isEndlessRunning(std::string
const&
name);
1570 template <
typename T>
1571 T parseFile(std::string
const& filename);
1573 void gatherStabilityInformation(std::vector<std::string>& warnings, std::vector<std::string>& recommendations);
1574 void printStabilityInformationOnce(std::ostream* os);
1577 uint64_t& singletonHeaderHash() noexcept;
1580 Clock::duration calcClockResolution(
size_t numEvaluations) noexcept;
1587 class NumSep : public std::numpunct<
char> {
1589 explicit NumSep(
char sep);
1590 char do_thousands_sep()
const override;
1591 std::string do_grouping()
const override;
1600 class StreamStateRestorer {
1602 explicit StreamStateRestorer(std::ostream& s);
1603 ~StreamStateRestorer();
1609 StreamStateRestorer(StreamStateRestorer
const&) =
delete;
1610 StreamStateRestorer& operator=(StreamStateRestorer
const&) =
delete;
1611 StreamStateRestorer(StreamStateRestorer&&) =
delete;
1612 StreamStateRestorer& operator=(StreamStateRestorer&&) =
delete;
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;
1627 Number(
int width,
int precision,
double value);
1628 Number(
int width,
int precision, int64_t value);
1629 std::string to_s()
const;
1632 friend std::ostream&
operator<<(std::ostream& os, Number
const& n);
1633 std::ostream& write(std::ostream& os)
const;
1641 std::string to_s(uint64_t s);
1643 std::ostream&
operator<<(std::ostream& os, Number
const& n);
1645 class MarkDownColumn {
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;
1657 std::string mSuffix;
1662 class MarkDownCode {
1664 explicit MarkDownCode(std::string
const& what);
1667 friend std::ostream&
operator<<(std::ostream& os, MarkDownCode
const& mdCode);
1668 std::ostream& write(std::ostream& os)
const;
1670 std::string mWhat{};
1673 std::ostream&
operator<<(std::ostream& os, MarkDownCode
const& mdCode);
1683 namespace nanobench {
1685 void render(
char const* mustacheTemplate, std::vector<Result>
const& results, std::ostream& out) {
1686 detail::fmt::StreamStateRestorer restorer(out);
1688 out.precision(std::numeric_limits<double>::digits10);
1689 auto nodes = templates::parseMustacheTemplate(&mustacheTemplate);
1691 for (
auto const& n : nodes) {
1694 case templates::Node::Type::content:
1695 out.write(n.begin, std::distance(n.begin, n.end));
1698 case templates::Node::Type::inverted_section:
1699 throw std::runtime_error(
"unknown list '" + std::string(n.begin, n.end) +
"'");
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);
1708 throw std::runtime_error(
"unknown section '" + std::string(n.begin, n.end) +
"'");
1712 case templates::Node::Type::tag:
1714 if (!generateConfigTag(n, results.back().config(), out)) {
1715 throw std::runtime_error(
"unknown tag '" + std::string(n.begin, n.end) +
"'");
1722 void render(
char const* mustacheTemplate,
const Bench& bench, std::ostream& out) {
1723 render(mustacheTemplate, bench.results(), out);
1729 # if defined(__clang__)
1730 # pragma clang diagnostic push
1731 # pragma clang diagnostic ignored "-Wexit-time-destructors"
1733 static PerformanceCounters pc;
1734 # if defined(__clang__)
1735 # pragma clang diagnostic pop
1744 # if defined(_MSC_VER)
1745 # pragma optimize("", off)
1746 void doNotOptimizeAwaySink(
void const*) {}
1747 # pragma optimize("", on)
1750 template <
typename T>
1751 T parseFile(std::string
const& filename) {
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.
1763 return std::getenv(name);
1764 # if defined(_MSC_VER)
1765 # pragma warning(pop)
1769 bool isEndlessRunning(std::string
const&
name) {
1770 auto endless = getEnv(
"NANOBENCH_ENDLESS");
1771 return nullptr != endless && endless ==
name;
1774 void gatherStabilityInformation(std::vector<std::string>& warnings, std::vector<std::string>& recommendations) {
1776 recommendations.clear();
1778 bool recommendCheckFlags =
false;
1781 warnings.emplace_back(
"DEBUG defined");
1782 recommendCheckFlags =
true;
1785 bool recommendPyPerf =
false;
1786 # if defined(__linux__)
1787 auto nprocs = sysconf(_SC_NPROCESSORS_CONF);
1789 warnings.emplace_back(
"couldn't figure out number of processors - no governor, turbo check possible");
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() +
1804 recommendPyPerf =
true;
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;
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;
1822 if (recommendCheckFlags) {
1823 recommendations.emplace_back(
"Make sure you compile for Release");
1825 if (recommendPyPerf) {
1826 recommendations.emplace_back(
"Use 'pyperf system tune' before benchmarking. See https://github.com/vstinner/pyperf");
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()) {
1842 os <<
"Warning, results might be unstable:" << std::endl;
1843 for (
auto const& w : warnings) {
1844 os <<
"* " << w << std::endl;
1847 os << std::endl <<
"Recommendations" << std::endl;
1848 for (
auto const& r : recommendations) {
1849 os <<
"* " << r << std::endl;
1855 uint64_t& singletonHeaderHash() noexcept {
1856 static uint64_t sHeaderHash{};
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);
1870 inline uint64_t hash_combine(uint64_t seed, uint64_t val) {
1871 return seed ^ (val + UINT64_C(0x9e3779b9) + (seed << 6U) + (seed >> 2U));
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) {
1883 }
while (tBegin == tEnd);
1884 bestDuration = (std::min)(bestDuration, tEnd - tBegin);
1886 return bestDuration;
1890 Clock::duration clockResolution() noexcept {
1891 static Clock::duration sResolution = calcClockResolution(20);
1896 struct IterationLogic::Impl {
1897 enum class State { warmup, upscaling_runtime, measuring, endless };
1899 explicit Impl(Bench
const& bench)
1901 , mResult(bench.config()) {
1902 printStabilityInformationOnce(mBench.output());
1905 mTargetRuntimePerEpoch = detail::clockResolution() * mBench.clockResolutionMultiple();
1906 if (mTargetRuntimePerEpoch > mBench.maxEpochTime()) {
1907 mTargetRuntimePerEpoch = mBench.maxEpochTime();
1909 if (mTargetRuntimePerEpoch < mBench.minEpochTime()) {
1910 mTargetRuntimePerEpoch = mBench.minEpochTime();
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()) {
1922 mNumIters = mBench.epochIterations();
1923 mState = State::measuring;
1925 mNumIters = mBench.minEpochIterations();
1926 mState = State::upscaling_runtime;
1932 auto doubleElapsed = d(elapsed);
1933 auto doubleTargetRuntimePerEpoch = d(mTargetRuntimePerEpoch);
1934 auto doubleNewIters = doubleTargetRuntimePerEpoch / doubleElapsed * d(iters);
1936 auto doubleMinEpochIters = d(mBench.minEpochIterations());
1937 if (doubleNewIters < doubleMinEpochIters) {
1938 doubleNewIters = doubleMinEpochIters;
1940 doubleNewIters *= 1.0 + 0.2 * mRng.uniform01();
1944 return static_cast<uint64_t
>(doubleNewIters + 0.5);
1948 if (elapsed * 10 < mTargetRuntimePerEpoch) {
1950 if (mNumIters * 10 < mNumIters) {
1952 showResult(
"iterations overflow. Maybe your code got optimized away?");
1958 mNumIters = calcBestNumIters(elapsed, mNumIters);
1962 void add(std::chrono::nanoseconds elapsed, PerformanceCounters
const& pc) noexcept {
1963 # if defined(ANKERL_NANOBENCH_LOG_ENABLED)
1964 auto oldIters = mNumIters;
1969 if (isCloseEnoughForMeasurements(elapsed)) {
1972 mState = State::measuring;
1973 mNumIters = calcBestNumIters(elapsed, mNumIters);
1976 mState = State::upscaling_runtime;
1981 case State::upscaling_runtime:
1982 if (isCloseEnoughForMeasurements(elapsed)) {
1984 mState = State::measuring;
1985 mTotalElapsed += elapsed;
1986 mTotalNumIters += mNumIters;
1987 mResult.add(elapsed, mNumIters, pc);
1988 mNumIters = calcBestNumIters(mTotalElapsed, mTotalNumIters);
1994 case State::measuring:
1997 mTotalElapsed += elapsed;
1998 mTotalNumIters += mNumIters;
1999 mResult.add(elapsed, mNumIters, pc);
2000 if (0 != mBench.epochIterations()) {
2001 mNumIters = mBench.epochIterations();
2003 mNumIters = calcBestNumIters(mTotalElapsed, mTotalNumIters);
2007 case State::endless:
2008 mNumIters = (std::numeric_limits<uint64_t>::max)();
2012 if (static_cast<uint64_t>(mResult.size()) == mBench.epochs()) {
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));
2024 void showResult(std::string
const& errorMessage)
const {
2027 if (mBench.output() !=
nullptr) {
2029 std::vector<fmt::MarkDownColumn> columns;
2033 if (mBench.relative()) {
2035 if (!mBench.results().empty()) {
2038 columns.emplace_back(11, 1,
"relative",
"%", d);
2041 if (mBench.complexityN() > 0) {
2042 columns.emplace_back(14, 0,
"complexityN",
"", mBench.complexityN());
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);
2049 columns.emplace_back(10, 1,
"err%",
"%", rErrorMedian * 100.0);
2051 double rInsMedian = -1.0;
2054 columns.emplace_back(18, 2,
"ins/" + mBench.unit(),
"", rInsMedian / mBench.batch());
2057 double rCycMedian = -1.0;
2060 columns.emplace_back(18, 2,
"cyc/" + mBench.unit(),
"", rCycMedian / mBench.batch());
2062 if (rInsMedian > 0.0 && rCycMedian > 0.0) {
2063 columns.emplace_back(9, 3,
"IPC",
"", rCycMedian <= 0.0 ? 0.0 : rInsMedian / rCycMedian);
2067 columns.emplace_back(17, 2,
"bra/" + mBench.unit(),
"", rBraMedian / mBench.batch());
2070 if (rBraMedian >= 1e-9) {
2073 columns.emplace_back(10, 1,
"miss%",
"%", p);
2080 auto& os = *mBench.output();
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);
2088 if (hash != singletonHeaderHash()) {
2089 singletonHeaderHash() = hash;
2093 for (
auto const& col : columns) {
2096 os <<
"| " << mBench.title() << std::endl;
2098 for (
auto const& col : columns) {
2099 os << col.separator();
2101 os <<
"|:" << std::string(mBench.title().size() + 1U,
'-') << std::endl;
2104 if (!errorMessage.empty()) {
2105 for (
auto const& col : columns) {
2106 os << col.invalid();
2108 os <<
"| :boom: " << fmt::MarkDownCode(mBench.name()) <<
" (" << errorMessage <<
')' << std::endl;
2110 for (
auto const& col : columns) {
2114 auto showUnstable = rErrorMedian >= 0.05;
2116 os <<
":wavy_dash: ";
2118 os << fmt::MarkDownCode(mBench.name());
2120 auto avgIters =
static_cast<double>(mTotalNumIters) / static_cast<double>(mBench.epochs());
2122 auto suggestedIters =
static_cast<uint64_t
>(avgIters * 10 + 0.5);
2124 os <<
" (Unstable with ~" << detail::fmt::Number(1, 1, avgIters)
2125 <<
" iters. Increase `minEpochIterations` to e.g. " << suggestedIters <<
")";
2133 return elapsed * 3 >= mTargetRuntimePerEpoch * 2;
2136 uint64_t mNumIters = 1;
2137 Bench
const& mBench;
2138 std::chrono::nanoseconds mTargetRuntimePerEpoch{};
2141 std::chrono::nanoseconds mTotalElapsed{};
2142 uint64_t mTotalNumIters = 0;
2144 State mState = State::upscaling_runtime;
2148 IterationLogic::IterationLogic(Bench const& bench) noexcept
2149 : mPimpl(new Impl(bench)) {}
2151 IterationLogic::~IterationLogic() {
2157 uint64_t IterationLogic::numIters() const noexcept {
2159 return mPimpl->mNumIters;
2162 void IterationLogic::add(std::chrono::nanoseconds elapsed, PerformanceCounters
const& pc) noexcept {
2163 mPimpl->add(elapsed, pc);
2166 void IterationLogic::moveResultTo(std::vector<Result>& results) noexcept {
2167 results.emplace_back(std::move(mPimpl->mResult));
2170 # if ANKERL_NANOBENCH(PERF_COUNTERS)
2173 class LinuxPerformanceCounters {
2176 Target(uint64_t* targetValue_,
bool correctMeasuringOverhead_,
bool correctLoopOverhead_)
2177 : targetValue(targetValue_)
2178 , correctMeasuringOverhead(correctMeasuringOverhead_)
2179 , correctLoopOverhead(correctLoopOverhead_) {}
2181 uint64_t* targetValue{};
2182 bool correctMeasuringOverhead{};
2183 bool correctLoopOverhead{};
2186 ~LinuxPerformanceCounters();
2189 inline void start() {}
2191 inline void stop() {}
2193 bool monitor(perf_sw_ids swId, Target target);
2194 bool monitor(perf_hw_id hwId, Target target);
2196 bool hasError() const noexcept {
2202 inline void beginMeasure() {
2208 mHasError = -1 == ioctl(mFd, PERF_EVENT_IOC_RESET, PERF_IOC_FLAG_GROUP);
2214 mHasError = -1 == ioctl(mFd, PERF_EVENT_IOC_ENABLE, PERF_IOC_FLAG_GROUP);
2217 inline void endMeasure() {
2223 mHasError = (-1 == ioctl(mFd, PERF_EVENT_IOC_DISABLE, PERF_IOC_FLAG_GROUP));
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);
2233 void updateResults(uint64_t numIters);
2236 template <
typename T>
2237 static inline T divRounded(T a, T divisor) {
2238 return (a + divisor / 2) / divisor;
2241 template <
typename Op>
2243 void calibrate(Op&& op) {
2245 for (
auto& v : mCalibratedOverhead) {
2250 auto newCalibration = mCalibratedOverhead;
2251 for (
auto& v : newCalibration) {
2252 v = (std::numeric_limits<uint64_t>::max)();
2254 for (
size_t iter = 0; iter < 100; ++iter) {
2262 for (
size_t i = 0; i < newCalibration.size(); ++i) {
2263 auto diff = mCounters[i];
2264 if (newCalibration[i] > diff) {
2265 newCalibration[i] = diff;
2270 mCalibratedOverhead = std::move(newCalibration);
2277 uint64_t
const numIters = 100000U + (std::random_device{}() & 3);
2278 uint64_t n = numIters;
2279 uint32_t x = 1234567;
2292 auto measure1 = mCounters;
2303 auto measure2 = mCounters;
2305 for (
size_t i = 0; i < mCounters.size(); ++i) {
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;
2311 mLoopOverhead[i] = divRounded(overhead, numIters);
2317 bool monitor(uint32_t type, uint64_t eventid, Target target);
2319 std::map<uint64_t, Target> mIdToTarget{};
2322 std::vector<uint64_t> mCounters{3};
2323 std::vector<uint64_t> mCalibratedOverhead{3};
2324 std::vector<uint64_t> mLoopOverhead{3};
2326 uint64_t mTimeEnabledNanos = 0;
2327 uint64_t mTimeRunningNanos = 0;
2329 bool mHasError =
false;
2333 LinuxPerformanceCounters::~LinuxPerformanceCounters() {
2339 bool LinuxPerformanceCounters::monitor(perf_sw_ids swId, LinuxPerformanceCounters::Target target) {
2340 return monitor(PERF_TYPE_SOFTWARE, swId, target);
2343 bool LinuxPerformanceCounters::monitor(perf_hw_id hwId, LinuxPerformanceCounters::Target target) {
2344 return monitor(PERF_TYPE_HARDWARE, hwId, target);
2349 void LinuxPerformanceCounters::updateResults(uint64_t numIters) {
2351 for (
auto& id_value : mIdToTarget) {
2352 *id_value.second.targetValue = UINT64_C(0);
2359 mTimeEnabledNanos = mCounters[1] - mCalibratedOverhead[1];
2360 mTimeRunningNanos = mCounters[2] - mCalibratedOverhead[2];
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];
2366 auto it = mIdToTarget.find(
id);
2367 if (
it != mIdToTarget.end()) {
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];
2375 *tgt.targetValue = 0U;
2378 if (tgt.correctLoopOverhead) {
2379 auto correctionVal = mLoopOverhead[idx] * numIters;
2380 if (*tgt.targetValue >= correctionVal) {
2381 *tgt.targetValue -= correctionVal;
2383 *tgt.targetValue = 0U;
2390 bool LinuxPerformanceCounters::monitor(uint32_t type, uint64_t eventid, Target target) {
2391 *target.targetValue = (std::numeric_limits<uint64_t>::max)();
2396 auto pea = perf_event_attr();
2397 std::memset(&pea, 0,
sizeof(perf_event_attr));
2399 pea.size =
sizeof(perf_event_attr);
2400 pea.config = eventid;
2402 pea.exclude_kernel = 1;
2406 pea.read_format = PERF_FORMAT_GROUP | PERF_FORMAT_ID | PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING;
2410 # if defined(PERF_FLAG_FD_CLOEXEC) // since Linux 3.14
2411 const unsigned long flags = PERF_FLAG_FD_CLOEXEC;
2413 const unsigned long flags = 0;
2416 auto fd =
static_cast<int>(syscall(__NR_perf_event_open, &pea, pid, cpu, mFd, flags));
2426 if (-1 == ioctl(fd, PERF_EVENT_IOC_ID, &
id)) {
2432 mIdToTarget.emplace(
id, target);
2435 auto size = 3 + 2 * mIdToTarget.size();
2436 mCounters.resize(size);
2437 mCalibratedOverhead.resize(size);
2438 mLoopOverhead.resize(size);
2443 PerformanceCounters::PerformanceCounters()
2444 : mPc(new LinuxPerformanceCounters())
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));
2466 if (mPc->hasError()) {
2468 mHas = PerfCountSet<bool>{};
2472 PerformanceCounters::~PerformanceCounters() {
2473 if (
nullptr != mPc) {
2478 void PerformanceCounters::beginMeasure() {
2479 mPc->beginMeasure();
2482 void PerformanceCounters::endMeasure() {
2486 void PerformanceCounters::updateResults(uint64_t numIters) {
2487 mPc->updateResults(numIters);
2492 PerformanceCounters::PerformanceCounters() =
default;
2493 PerformanceCounters::~PerformanceCounters() =
default;
2494 void PerformanceCounters::beginMeasure() {}
2495 void PerformanceCounters::endMeasure() {}
2496 void PerformanceCounters::updateResults(uint64_t) {}
2511 NumSep::NumSep(
char sep)
2514 char NumSep::do_thousands_sep()
const {
2518 std::string NumSep::do_grouping()
const {
2523 StreamStateRestorer::StreamStateRestorer(std::ostream& s)
2525 , mLocale(s.getloc())
2526 , mPrecision(s.precision())
2529 , mFmtFlags(s.flags()) {}
2531 StreamStateRestorer::~StreamStateRestorer() {
2536 void StreamStateRestorer::restore() {
2537 mStream.imbue(mLocale);
2538 mStream.precision(mPrecision);
2539 mStream.width(mWidth);
2540 mStream.fill(mFill);
2541 mStream.flags(mFmtFlags);
2544 Number::Number(
int width,
int precision, int64_t value)
2546 , mPrecision(precision)
2547 , mValue(static_cast<double>(value)) {}
2549 Number::Number(
int width,
int precision,
double value)
2551 , mPrecision(precision)
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;
2561 std::string Number::to_s()
const {
2562 std::stringstream ss;
2567 std::string to_s(uint64_t n) {
2570 str +=
static_cast<char>(
'0' +
static_cast<char>(n % 10));
2573 std::reverse(str.begin(), str.end());
2577 std::ostream&
operator<<(std::ostream& os, Number
const& n) {
2581 MarkDownColumn::MarkDownColumn(
int w,
int prec, std::string
const& tit, std::string
const& suff,
double val)
2588 std::string MarkDownColumn::title()
const {
2589 std::stringstream ss;
2590 ss <<
'|' << std::setw(mWidth - 2) << std::right << mTitle <<
' ';
2594 std::string MarkDownColumn::separator()
const {
2595 std::string sep(static_cast<size_t>(mWidth),
'-');
2601 std::string MarkDownColumn::invalid()
const {
2602 std::string sep(static_cast<size_t>(mWidth),
' ');
2604 sep[sep.size() - 2] =
'-';
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 <<
' ';
2616 MarkDownCode::MarkDownCode(std::string
const& what) {
2617 mWhat.reserve(what.size() + 2);
2618 mWhat.push_back(
'`');
2619 for (
char c : what) {
2622 mWhat.push_back(
'`');
2625 mWhat.push_back(
'`');
2628 std::ostream& MarkDownCode::write(std::ostream& os)
const {
2632 std::ostream&
operator<<(std::ostream& os, MarkDownCode
const& mdCode) {
2633 return mdCode.write(os);
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;
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);
2662 : mConfig(benchmarkConfig)
2665 void Result::add(Clock::duration totalElapsed, uint64_t iters, detail::PerformanceCounters
const& pc) {
2669 double dIters = d(iters);
2670 mNameToMeasurements[u(Result::Measure::iterations)].push_back(dIters);
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);
2676 if (pc.has().cpuCycles) {
2677 mNameToMeasurements[u(Result::Measure::cpucycles)].push_back(d(pc.val().cpuCycles) / dIters);
2679 if (pc.has().contextSwitches) {
2680 mNameToMeasurements[u(Result::Measure::contextswitches)].push_back(d(pc.val().contextSwitches) / dIters);
2682 if (pc.has().instructions) {
2683 mNameToMeasurements[u(Result::Measure::instructions)].push_back(d(pc.val().instructions) / dIters);
2685 if (pc.has().branchInstructions) {
2686 double branchInstructions = 0.0;
2688 if (pc.val().branchInstructions > iters + 1U) {
2689 branchInstructions = d(pc.val().branchInstructions - (iters + 1U));
2691 mNameToMeasurements[u(Result::Measure::branchinstructions)].push_back(branchInstructions / dIters);
2693 if (pc.has().branchMisses) {
2695 double branchMisses = d(pc.val().branchMisses);
2696 if (branchMisses > branchInstructions) {
2698 branchMisses = branchInstructions;
2702 branchMisses -= 1.0;
2703 if (branchMisses < 1.0) {
2706 mNameToMeasurements[u(Result::Measure::branchmisses)].push_back(branchMisses / dIters);
2711 Config
const& Result::config() const noexcept {
2715 inline double calcMedian(std::vector<double>& data) {
2719 std::sort(data.begin(), data.end());
2721 auto midIdx = data.size() / 2U;
2722 if (1U == (data.size() & 1U)) {
2723 return data[midIdx];
2725 return (data[midIdx - 1U] + data[midIdx]) / 2U;
2728 double Result::median(Measure m)
const {
2730 auto data = mNameToMeasurements[detail::u(m)];
2731 return calcMedian(data);
2734 double Result::average(Measure m)
const {
2736 auto const& data = mNameToMeasurements[detail::u(m)];
2742 return sum(m) / d(data.size());
2745 double Result::medianAbsolutePercentError(Measure m)
const {
2747 auto data = mNameToMeasurements[detail::u(m)];
2751 auto med = calcMedian(data);
2754 for (
auto& x : data) {
2760 return calcMedian(data);
2764 auto const& data = mNameToMeasurements[detail::u(m)];
2765 return std::accumulate(data.begin(), data.end(), 0.0);
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)];
2772 if (data1.size() != data2.size()) {
2776 double result = 0.0;
2777 for (
size_t i = 0, s = data1.size(); i != s; ++i) {
2778 result += data1[i] * data2[i];
2783 bool Result::has(Measure m)
const noexcept {
2784 return !mNameToMeasurements[detail::u(m)].empty();
2787 double Result::get(
size_t idx, Measure m)
const {
2788 auto const& data = mNameToMeasurements[detail::u(m)];
2789 return data.at(idx);
2792 bool Result::empty() const noexcept {
2793 return 0U == size();
2796 size_t Result::size() const noexcept {
2797 auto const& data = mNameToMeasurements[detail::u(Measure::elapsed)];
2801 double Result::minimum(Measure m)
const noexcept {
2802 auto const& data = mNameToMeasurements[detail::u(m)];
2808 return *std::min_element(data.begin(), data.end());
2811 double Result::maximum(Measure m)
const noexcept {
2812 auto const& data = mNameToMeasurements[detail::u(m)];
2818 return *std::max_element(data.begin(), data.end());
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;
2840 return Measure::_size;
2846 mConfig.mOut = &std::cout;
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;
2855 double Bench::batch() const noexcept {
2856 return mConfig.mBatch;
2859 double Bench::complexityN() const noexcept {
2860 return mConfig.mComplexityN;
2865 Bench& Bench::relative(
bool isRelativeEnabled) noexcept {
2866 mConfig.mIsRelative = isRelativeEnabled;
2869 bool Bench::relative() const noexcept {
2870 return mConfig.mIsRelative;
2874 mConfig.mShowPerformanceCounters = showPerformanceCounters;
2878 return mConfig.mShowPerformanceCounters;
2884 Bench& Bench::unit(
char const* u) {
2885 if (u != mConfig.mUnit) {
2892 Bench& Bench::unit(std::string
const& u) {
2893 return unit(u.c_str());
2896 std::string
const& Bench::unit() const noexcept {
2897 return mConfig.mUnit;
2901 Bench& Bench::title(
const char* benchmarkTitle) {
2902 if (benchmarkTitle != mConfig.mBenchmarkTitle) {
2905 mConfig.mBenchmarkTitle = benchmarkTitle;
2908 Bench& Bench::title(std::string
const& benchmarkTitle) {
2909 if (benchmarkTitle != mConfig.mBenchmarkTitle) {
2912 mConfig.mBenchmarkTitle = benchmarkTitle;
2916 std::string
const& Bench::title() const noexcept {
2917 return mConfig.mBenchmarkTitle;
2921 mConfig.mBenchmarkName = benchmarkName;
2925 Bench&
Bench::name(std::string
const& benchmarkName) {
2926 mConfig.mBenchmarkName = benchmarkName;
2931 return mConfig.mBenchmarkName;
2935 Bench& Bench::epochs(
size_t numEpochs) noexcept {
2936 mConfig.mNumEpochs = numEpochs;
2939 size_t Bench::epochs() const noexcept {
2940 return mConfig.mNumEpochs;
2944 Bench& Bench::clockResolutionMultiple(
size_t multiple) noexcept {
2945 mConfig.mClockResolutionMultiple = multiple;
2948 size_t Bench::clockResolutionMultiple() const noexcept {
2949 return mConfig.mClockResolutionMultiple;
2953 Bench& Bench::maxEpochTime(std::chrono::nanoseconds t) noexcept {
2954 mConfig.mMaxEpochTime = t;
2957 std::chrono::nanoseconds Bench::maxEpochTime() const noexcept {
2958 return mConfig.mMaxEpochTime;
2962 Bench& Bench::minEpochTime(std::chrono::nanoseconds t) noexcept {
2963 mConfig.mMinEpochTime = t;
2966 std::chrono::nanoseconds Bench::minEpochTime() const noexcept {
2967 return mConfig.mMinEpochTime;
2970 Bench& Bench::minEpochIterations(uint64_t numIters) noexcept {
2971 mConfig.mMinEpochIterations = (numIters == 0) ? 1 : numIters;
2974 uint64_t Bench::minEpochIterations() const noexcept {
2975 return mConfig.mMinEpochIterations;
2978 Bench& Bench::epochIterations(uint64_t numIters) noexcept {
2979 mConfig.mEpochIterations = numIters;
2982 uint64_t Bench::epochIterations() const noexcept {
2983 return mConfig.mEpochIterations;
2986 Bench& Bench::warmup(uint64_t numWarmupIters) noexcept {
2987 mConfig.mWarmup = numWarmupIters;
2990 uint64_t Bench::warmup() const noexcept {
2991 return mConfig.mWarmup;
2994 Bench& Bench::config(Config
const& benchmarkConfig) {
2995 mConfig = benchmarkConfig;
2998 Config
const& Bench::config() const noexcept {
3002 Bench& Bench::output(std::ostream* outstream) noexcept {
3003 mConfig.mOut = outstream;
3008 return mConfig.mOut;
3011 std::vector<Result>
const& Bench::results() const noexcept {
3015 Bench&
Bench::render(
char const* templateContent, std::ostream& os) {
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) {
3026 bigOs.emplace_back(
"O(n)", rangeMeasure, [](
double n) {
3029 bigOs.emplace_back(
"O(log n)", rangeMeasure, [](
double n) {
3030 return std::log2(n);
3032 bigOs.emplace_back(
"O(n log n)", rangeMeasure, [](
double n) {
3033 return n * std::log2(n);
3035 bigOs.emplace_back(
"O(n^2)", rangeMeasure, [](
double n) {
3038 bigOs.emplace_back(
"O(n^3)", rangeMeasure, [](
double n) {
3041 std::sort(bigOs.begin(), bigOs.end());
3048 std::random_device rd;
3049 std::uniform_int_distribution<uint64_t> dist;
3053 }
while (mX == 0 && mY == 0);
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);
3065 Rng::Rng(uint64_t seed) noexcept
3066 : mX(splitMix64(seed))
3067 , mY(splitMix64(seed)) {
3068 for (
size_t i = 0; i < 10; ++i) {
3074 Rng::Rng(uint64_t x, uint64_t y) noexcept
3078 Rng Rng::copy() const noexcept {
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));
3089 return rangeMeasure;
3092 BigO::BigO(std::string
const& bigOName, RangeMeasure
const& rangeMeasure)
3096 double sumRangeMeasure = 0.0;
3097 double sumRangeRange = 0.0;
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;
3103 mConstant = sumRangeMeasure / sumRangeRange;
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;
3112 sumMeasure += rangeMeasure[i].second;
3115 auto n =
static_cast<double>(rangeMeasure.size());
3116 auto mean = sumMeasure / n;
3117 mNormalizedRootMeanSquare = std::sqrt(err / n) / mean;
3120 BigO::BigO(
const char* bigOName, RangeMeasure
const& rangeMeasure)
3121 : BigO(std::string(bigOName), rangeMeasure) {}
3123 std::string
const&
BigO::name() const noexcept {
3127 double BigO::constant() const noexcept {
3131 double BigO::normalizedRootMeanSquare() const noexcept {
3132 return mNormalizedRootMeanSquare;
3136 return std::tie(mNormalizedRootMeanSquare, mName) < std::tie(other.mNormalizedRootMeanSquare, other.mName);
3139 std::ostream&
operator<<(std::ostream& os, BigO
const& bigO) {
3140 return os << bigO.constant() <<
" * " << bigO.name() <<
", rms=" << bigO.normalizedRootMeanSquare();
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();
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)
std::deque< CInv >::iterator it
const std::chrono::seconds now
std::vector< std::pair< double, double >> RangeMeasure
bool operator==(const CNetAddr &a, const CNetAddr &b)
static RangeMeasure collectRangeMeasure(std::vector< Result > const &results)
void add(std::chrono::nanoseconds elapsed, PerformanceCounters const &pc) noexcept
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.
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.
State
The various states a (txhash,peer) pair can be in.
std::ostream & operator<<(std::ostream &os, BigO const &bigO)
std::enable_if<!doNotOptimizeNeedsIndirect< T >)>::type doNotOptimizeAway(T const &val)
#define ANKERL_NANOBENCH_NO_SANITIZE(...)
Bench & run(char const *benchmarkName, Op &&op)
Repeatedly calls op() based on the configuration, and performs measurements.
BigO(std::string const &bigOName, RangeMeasure const &rangeMeasure, Op rangeToN)
void doNotOptimizeAway(Arg &&arg)
Makes sure none of the given arguments are optimized away by the compiler.
Bench & complexityN(T b) noexcept
static constexpr uint64_t rotl(uint64_t x, unsigned k) noexcept
std::conditional< std::chrono::high_resolution_clock::is_steady, std::chrono::high_resolution_clock, std::chrono::steady_clock >::type Clock
static Measure fromString(std::string const &str)
#define ANKERL_NANOBENCH(x)
constexpr bool doNotOptimizeNeedsIndirect()
char const * csv() noexcept
CSV data for the benchmark results.
void shuffle(Container &container) noexcept
Shuffles all entries in the given container.
bool operator<(const CNetAddr &a, const CNetAddr &b)
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)
uint64_t result_type
This RNG provides 64bit randomness.
Main entry point to nanobench's benchmarking facility.
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)
#define ANKERL_NANOBENCH_IS_TRIVIALLY_COPYABLE(...)