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 // In case high_resolution_clock is steady, prefer that, otherwise use steady_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
;
53 time_point beginTime
, lastTime
;
54 duration minTime
, maxTime
;
62 State(std::string _name
, duration _maxElapsed
) :
64 maxElapsed(_maxElapsed
),
65 minTime(duration::max()),
66 maxTime(duration::zero()),
71 minCycles(std::numeric_limits
<uint64_t>::max()),
72 maxCycles(std::numeric_limits
<uint64_t>::min()) {
77 typedef std::function
<void(State
&)> BenchFunction
;
81 typedef std::map
<std::string
, BenchFunction
> BenchmarkMap
;
82 static BenchmarkMap
&benchmarks();
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