Line data Source code
1 : // Copyright (c) 2015 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.
4 : #ifndef BITCOIN_BENCH_H
5 : #define BITCOIN_BENCH_H
6 :
7 : // Simple micro-benchmarking framework; API mostly matches a subset of the Google Benchmark
8 : // framework (see https://github.com/google/benchmark)
9 : // Wny not use the Google Benchmark framework? Because adding Yet Another Dependency
10 : // (that uses cmake as its build system and has lots of features we don't need) isn't
11 : // worth it.
12 :
13 : /*
14 : * Usage:
15 :
16 : static void CODE_TO_TIME(benchmark::State& state)
17 : {
18 : ... do any setup needed...
19 : while (state.KeepRunning()) {
20 : ... do stuff you want to time...
21 : }
22 : ... do any cleanup needed...
23 : }
24 :
25 : BENCHMARK(CODE_TO_TIME);
26 :
27 : */
28 :
29 :
30 : #include <boost/function.hpp>
31 : #include <boost/preprocessor/cat.hpp>
32 : #include <boost/preprocessor/stringize.hpp>
33 : #include <map>
34 : #include <string>
35 :
36 : namespace benchmark {
37 :
38 0 : class State {
39 : std::string name;
40 : double maxElapsed;
41 : double beginTime;
42 : double lastTime, minTime, maxTime;
43 : int64_t count;
44 : int64_t timeCheckCount;
45 : public:
46 0 : State(std::string _name, double _maxElapsed) : name(_name), maxElapsed(_maxElapsed), count(0) {
47 0 : minTime = std::numeric_limits<double>::max();
48 0 : maxTime = std::numeric_limits<double>::min();
49 0 : timeCheckCount = 1;
50 0 : }
51 : bool KeepRunning();
52 : };
53 :
54 : typedef boost::function<void(State&)> BenchFunction;
55 :
56 : class BenchRunner
57 : {
58 : static std::map<std::string, BenchFunction> benchmarks;
59 :
60 : public:
61 : BenchRunner(std::string name, BenchFunction func);
62 :
63 : static void RunAll(double elapsedTimeForOne=1.0);
64 : };
65 : }
66 :
67 : // BENCHMARK(foo) expands to: benchmark::BenchRunner bench_11foo("foo", foo);
68 : #define BENCHMARK(n) \
69 : benchmark::BenchRunner BOOST_PP_CAT(bench_, BOOST_PP_CAT(__LINE__, n))(BOOST_PP_STRINGIZE(n), n);
70 :
71 : #endif // BITCOIN_BENCH_H
|