xref: /aosp_15_r20/external/google-benchmark/test/benchmark_min_time_flag_iters_test.cc (revision dbb99499c3810fa1611fa2242a2fc446be01a57c)
1 #include <cassert>
2 #include <cstdlib>
3 #include <cstring>
4 #include <iostream>
5 #include <string>
6 #include <vector>
7 
8 #include "benchmark/benchmark.h"
9 
10 // Tests that we can specify the number of iterations with
11 // --benchmark_min_time=<NUM>x.
12 namespace {
13 
14 class TestReporter : public benchmark::ConsoleReporter {
15  public:
ReportContext(const Context & context)16   virtual bool ReportContext(const Context& context) BENCHMARK_OVERRIDE {
17     return ConsoleReporter::ReportContext(context);
18   };
19 
ReportRuns(const std::vector<Run> & report)20   virtual void ReportRuns(const std::vector<Run>& report) BENCHMARK_OVERRIDE {
21     assert(report.size() == 1);
22     iter_nums_.push_back(report[0].iterations);
23     ConsoleReporter::ReportRuns(report);
24   };
25 
TestReporter()26   TestReporter() {}
27 
~TestReporter()28   virtual ~TestReporter() {}
29 
GetIters() const30   const std::vector<benchmark::IterationCount>& GetIters() const {
31     return iter_nums_;
32   }
33 
34  private:
35   std::vector<benchmark::IterationCount> iter_nums_;
36 };
37 
38 }  // end namespace
39 
BM_MyBench(benchmark::State & state)40 static void BM_MyBench(benchmark::State& state) {
41   for (auto s : state) {
42   }
43 }
44 BENCHMARK(BM_MyBench);
45 
main(int argc,char ** argv)46 int main(int argc, char** argv) {
47   // Make a fake argv and append the new --benchmark_min_time=<foo> to it.
48   int fake_argc = argc + 1;
49   const char** fake_argv = new const char*[static_cast<size_t>(fake_argc)];
50   for (int i = 0; i < argc; ++i) fake_argv[i] = argv[i];
51   fake_argv[argc] = "--benchmark_min_time=4x";
52 
53   benchmark::Initialize(&fake_argc, const_cast<char**>(fake_argv));
54 
55   TestReporter test_reporter;
56   const size_t returned_count =
57       benchmark::RunSpecifiedBenchmarks(&test_reporter, "BM_MyBench");
58   assert(returned_count == 1);
59 
60   // Check the executed iters.
61   const std::vector<benchmark::IterationCount> iters = test_reporter.GetIters();
62   assert(!iters.empty() && iters[0] == 4);
63 
64   delete[] fake_argv;
65   return 0;
66 }
67