Merge #11583: Do not make it trivial for inbound peers to generate log entries
[bitcoinplatinum.git] / src / bench / bench.h
blob071a5dc9c7ae991b7df957bfd458a94f1105d8f2
1 // Copyright (c) 2015-2016 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_BENCH_BENCH_H
6 #define BITCOIN_BENCH_BENCH_H
8 #include <functional>
9 #include <limits>
10 #include <map>
11 #include <string>
12 #include <chrono>
14 #include <boost/preprocessor/cat.hpp>
15 #include <boost/preprocessor/stringize.hpp>
17 // Simple micro-benchmarking framework; API mostly matches a subset of the Google Benchmark
18 // framework (see https://github.com/google/benchmark)
19 // Why not use the Google Benchmark framework? Because adding Yet Another Dependency
20 // (that uses cmake as its build system and has lots of features we don't need) isn't
21 // worth it.
24 * Usage:
26 static void CODE_TO_TIME(benchmark::State& state)
28 ... do any setup needed...
29 while (state.KeepRunning()) {
30 ... do stuff you want to time...
32 ... do any cleanup needed...
35 BENCHMARK(CODE_TO_TIME);
39 namespace benchmark {
40 // In case high_resolution_clock is steady, prefer that, otherwise use steady_clock.
41 struct best_clock {
42 using hi_res_clock = std::chrono::high_resolution_clock;
43 using steady_clock = std::chrono::steady_clock;
44 using type = std::conditional<hi_res_clock::is_steady, hi_res_clock, steady_clock>::type;
46 using clock = best_clock::type;
47 using time_point = clock::time_point;
48 using duration = clock::duration;
50 class State {
51 std::string name;
52 duration maxElapsed;
53 time_point beginTime, lastTime;
54 duration minTime, maxTime;
55 uint64_t count;
56 uint64_t countMask;
57 uint64_t beginCycles;
58 uint64_t lastCycles;
59 uint64_t minCycles;
60 uint64_t maxCycles;
61 public:
62 State(std::string _name, duration _maxElapsed) :
63 name(_name),
64 maxElapsed(_maxElapsed),
65 minTime(duration::max()),
66 maxTime(duration::zero()),
67 count(0),
68 countMask(1),
69 beginCycles(0),
70 lastCycles(0),
71 minCycles(std::numeric_limits<uint64_t>::max()),
72 maxCycles(std::numeric_limits<uint64_t>::min()) {
74 bool KeepRunning();
77 typedef std::function<void(State&)> BenchFunction;
79 class BenchRunner
81 typedef std::map<std::string, BenchFunction> BenchmarkMap;
82 static BenchmarkMap &benchmarks();
84 public:
85 BenchRunner(std::string name, BenchFunction func);
87 static void RunAll(duration elapsedTimeForOne = std::chrono::seconds(1));
91 // BENCHMARK(foo) expands to: benchmark::BenchRunner bench_11foo("foo", foo);
92 #define BENCHMARK(n) \
93 benchmark::BenchRunner BOOST_PP_CAT(bench_, BOOST_PP_CAT(__LINE__, n))(BOOST_PP_STRINGIZE(n), n);
95 #endif // BITCOIN_BENCH_BENCH_H