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
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
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);
40 // On many systems, the high_resolution_clock offers no better resolution than the steady_clock.
41 // If that's the case, prefer the steady_clock.
43 using hi_res_clock
= std::chrono::high_resolution_clock
;
44 using steady_clock
= std::chrono::steady_clock
;
45 static constexpr bool steady_is_high_res
= std::ratio_less_equal
<steady_clock::period
, hi_res_clock::period
>::value
;
46 using type
= std::conditional
<steady_is_high_res
, steady_clock
, hi_res_clock
>::type
;
48 using clock
= best_clock::type
;
49 using time_point
= clock::time_point
;
50 using duration
= clock::duration
;
55 time_point beginTime
, lastTime
;
56 duration minTime
, maxTime
;
64 State(std::string _name
, duration _maxElapsed
) : name(_name
), maxElapsed(_maxElapsed
), count(0) {
65 minTime
= duration::max();
66 maxTime
= duration::zero();
67 minCycles
= std::numeric_limits
<uint64_t>::max();
68 maxCycles
= std::numeric_limits
<uint64_t>::min();
74 typedef std::function
<void(State
&)> BenchFunction
;
78 typedef std::map
<std::string
, BenchFunction
> BenchmarkMap
;
79 static BenchmarkMap
&benchmarks();
82 BenchRunner(std::string name
, BenchFunction func
);
84 static void RunAll(duration elapsedTimeForOne
= std::chrono::seconds(1));
88 // BENCHMARK(foo) expands to: benchmark::BenchRunner bench_11foo("foo", foo);
89 #define BENCHMARK(n) \
90 benchmark::BenchRunner BOOST_PP_CAT(bench_, BOOST_PP_CAT(__LINE__, n))(BOOST_PP_STRINGIZE(n), n);
92 #endif // BITCOIN_BENCH_BENCH_H