You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

bench.h 2.3KB

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