10 c++ benchmarking google-api parameter-passing google-benchmark
我有一个 C++ Google 基准测试程序。它使用谷歌的BENCHMARK_MAIN()方法。现在我用 Go 脚本调用并执行编译后的程序。有没有办法将参数传递到我的基准程序中?(我知道 main 方法的常见方法,但我不确定如何在 Googletest 中执行此操作,因为它是在中实现的benchmark_api.h,我不能只是更改它。)
更新:
到目前为止,我将宏主体复制到我的宏主体中benchmark.cpp并添加了一行。这不是一个很好的解决方案,因为 Google 对此宏的可能更改(例如名称更改或添加的代码行)不会影响我的副本。它终于起作用了。
int main (int argc, char** argv)
{
MyNamespace::conf = {argv[1]};
::benchmark::Initialize (&argc, argv);
::benchmark::RunSpecifiedBenchmarks ();
}
Run Code Online (Sandbox Code Playgroud)
破解整个BENCHMARK_MAIN功能当然是一种方法,但在我看来,这真的很麻烦而且很难看。所以我只想提出一种不同的方法:
// define your chunksize and iteration count combinations here (for i and j)
static void CustomArguments(benchmark::internal::Benchmark* b) {
for (int i = 0; i <= 10; ++i)
for (int j = 0; j <= 50; ++j)
b->Args({i, j});
}
// the string (name of the used function is passed later)
static void TestBenchmark(benchmark::State& state, std::string func_name) {
// cout for testing purposes
std::cout << state.range(0) /* = i */ << " " << state.range(1) /* = j */
<< " " << func_name << std::endl;
for (auto _ : state) {
// do whatever with i and j and func_name
}
}
// This macro is used to pass the string "function_name1/2/3"
// as a parameter to TestBenchmark
BENCHMARK_CAPTURE(TestBenchmark, benchmark_name1, "function_name1")
->Apply(CustomArguments);
BENCHMARK_CAPTURE(TestBenchmark, benchmark_name2, "function_name2")
->Apply(CustomArguments);
BENCHMARK_CAPTURE(TestBenchmark, benchmark_name3, "function_name3")
->Apply(CustomArguments);
BENCHMARK_MAIN()
Run Code Online (Sandbox Code Playgroud)
然后在您的 go 脚本中,您使用正则表达式过滤器调用基准测试:
./prog_name --benchmark_filter=InsertRegexFilterHere
例如:
./prog_name --benchmark_filter=TestBenchmark/benchmark_name2/5/35
上面的示例将调用基准测试并传递“function_name2”、5和35(这些是块大小和迭代计数的值),因此输出将类似于:
------------------------------------------------------------------------------
Benchmark Time CPU Iterations
------------------------------------------------------------------------------
TestBenchmark/benchmark_name2/5/35 2 ns 2 ns 308047644
Run Code Online (Sandbox Code Playgroud)