Use unique_ptr for pdbCopy (Db) and fix potential memory leak
[bitcoinplatinum.git] / src / bench / bench.h
blobd276f4ee91f4ec2b1edf2fa596cb34a6b95b91cc
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 // 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.
42 struct best_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;
52 class State {
53 std::string name;
54 duration maxElapsed;
55 time_point beginTime, lastTime;
56 duration minTime, maxTime;
57 uint64_t count;
58 uint64_t countMask;
59 uint64_t beginCycles;
60 uint64_t lastCycles;
61 uint64_t minCycles;
62 uint64_t maxCycles;
63 public:
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();
69 countMask = 1;
71 bool KeepRunning();
74 typedef std::function<void(State&)> BenchFunction;
76 class BenchRunner
78 typedef std::map<std::string, BenchFunction> BenchmarkMap;
79 static BenchmarkMap &benchmarks();
81 public:
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