|
| 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 | +#include "bench.h" |
| 5 | +#include <iostream> |
| 6 | +#include <sys/time.h> |
| 7 | + |
| 8 | +using namespace benchmark; |
| 9 | + |
| 10 | +std::map<std::string, BenchFunction> BenchRunner::benchmarks; |
| 11 | + |
| 12 | +static double gettimedouble(void) { |
| 13 | + struct timeval tv; |
| 14 | + gettimeofday(&tv, NULL); |
| 15 | + return tv.tv_usec * 0.000001 + tv.tv_sec; |
| 16 | +} |
| 17 | + |
| 18 | +BenchRunner::BenchRunner(std::string name, BenchFunction func) |
| 19 | +{ |
| 20 | + benchmarks.insert(std::make_pair(name, func)); |
| 21 | +} |
| 22 | + |
| 23 | +void |
| 24 | +BenchRunner::RunAll(double elapsedTimeForOne) |
| 25 | +{ |
| 26 | + std::cout << "Benchmark" << "," << "count" << "," << "min" << "," << "max" << "," << "average" << "\n"; |
| 27 | + |
| 28 | + for (std::map<std::string,BenchFunction>::iterator it = benchmarks.begin(); |
| 29 | + it != benchmarks.end(); ++it) { |
| 30 | + |
| 31 | + State state(it->first, elapsedTimeForOne); |
| 32 | + BenchFunction& func = it->second; |
| 33 | + func(state); |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +bool State::KeepRunning() |
| 38 | +{ |
| 39 | + double now; |
| 40 | + if (count == 0) { |
| 41 | + beginTime = now = gettimedouble(); |
| 42 | + } |
| 43 | + else { |
| 44 | + // timeCheckCount is used to avoid calling gettime most of the time, |
| 45 | + // so benchmarks that run very quickly get consistent results. |
| 46 | + if ((count+1)%timeCheckCount != 0) { |
| 47 | + ++count; |
| 48 | + return true; // keep going |
| 49 | + } |
| 50 | + now = gettimedouble(); |
| 51 | + double elapsedOne = (now - lastTime)/timeCheckCount; |
| 52 | + if (elapsedOne < minTime) minTime = elapsedOne; |
| 53 | + if (elapsedOne > maxTime) maxTime = elapsedOne; |
| 54 | + if (elapsedOne*timeCheckCount < maxElapsed/16) timeCheckCount *= 2; |
| 55 | + } |
| 56 | + lastTime = now; |
| 57 | + ++count; |
| 58 | + |
| 59 | + if (now - beginTime < maxElapsed) return true; // Keep going |
| 60 | + |
| 61 | + --count; |
| 62 | + |
| 63 | + // Output results |
| 64 | + double average = (now-beginTime)/count; |
| 65 | + std::cout << name << "," << count << "," << minTime << "," << maxTime << "," << average << "\n"; |
| 66 | + |
| 67 | + return false; |
| 68 | +} |
0 commit comments