1 #include <cassert>
2 #include <climits>
3 #include <cmath>
4 #include <cstdlib>
5 #include <cstring>
6 #include <iostream>
7 #include <string>
8 #include <vector>
9
10 #include "benchmark/benchmark.h"
11
12 // Tests that we can specify the min time with
13 // --benchmark_min_time=<NUM> (no suffix needed) OR
14 // --benchmark_min_time=<NUM>s
15 namespace {
16
17 // This is from benchmark.h
18 typedef int64_t IterationCount;
19
20 class TestReporter : public benchmark::ConsoleReporter {
21 public:
ReportContext(const Context & context)22 virtual bool ReportContext(const Context& context) BENCHMARK_OVERRIDE {
23 return ConsoleReporter::ReportContext(context);
24 };
25
ReportRuns(const std::vector<Run> & report)26 virtual void ReportRuns(const std::vector<Run>& report) BENCHMARK_OVERRIDE {
27 assert(report.size() == 1);
28 ConsoleReporter::ReportRuns(report);
29 };
30
ReportRunsConfig(double min_time,bool,IterationCount)31 virtual void ReportRunsConfig(double min_time, bool /* has_explicit_iters */,
32 IterationCount /* iters */) BENCHMARK_OVERRIDE {
33 min_times_.push_back(min_time);
34 }
35
TestReporter()36 TestReporter() {}
37
~TestReporter()38 virtual ~TestReporter() {}
39
GetMinTimes() const40 const std::vector<double>& GetMinTimes() const { return min_times_; }
41
42 private:
43 std::vector<double> min_times_;
44 };
45
AlmostEqual(double a,double b)46 bool AlmostEqual(double a, double b) {
47 return std::fabs(a - b) < std::numeric_limits<double>::epsilon();
48 }
49
DoTestHelper(int * argc,const char ** argv,double expected)50 void DoTestHelper(int* argc, const char** argv, double expected) {
51 benchmark::Initialize(argc, const_cast<char**>(argv));
52
53 TestReporter test_reporter;
54 const size_t returned_count =
55 benchmark::RunSpecifiedBenchmarks(&test_reporter, "BM_MyBench");
56 assert(returned_count == 1);
57
58 // Check the min_time
59 const std::vector<double>& min_times = test_reporter.GetMinTimes();
60 assert(!min_times.empty() && AlmostEqual(min_times[0], expected));
61 }
62
63 } // end namespace
64
BM_MyBench(benchmark::State & state)65 static void BM_MyBench(benchmark::State& state) {
66 for (auto s : state) {
67 }
68 }
69 BENCHMARK(BM_MyBench);
70
main(int argc,char ** argv)71 int main(int argc, char** argv) {
72 // Make a fake argv and append the new --benchmark_min_time=<foo> to it.
73 int fake_argc = argc + 1;
74 const char** fake_argv = new const char*[static_cast<size_t>(fake_argc)];
75
76 for (int i = 0; i < argc; ++i) fake_argv[i] = argv[i];
77
78 const char* no_suffix = "--benchmark_min_time=4";
79 const char* with_suffix = "--benchmark_min_time=4.0s";
80 double expected = 4.0;
81
82 fake_argv[argc] = no_suffix;
83 DoTestHelper(&fake_argc, fake_argv, expected);
84
85 fake_argv[argc] = with_suffix;
86 DoTestHelper(&fake_argc, fake_argv, expected);
87
88 delete[] fake_argv;
89 return 0;
90 }
91