谷歌基准自定义设置和拆卸方法

Google Benchmark Custom Setup And Teardown Method

本文关键字:方法 设置 基准 自定义 谷歌      更新时间:2023-10-16

我正在使用基准库来对一些代码进行基准测试。我想在调用实际基准代码一次之前调用一个设置方法,而不是每次都重复,用于多次基准测试方法调用。例如:

static void BM_SomeFunction(benchmark::State& state) {
// Perform setup here
for (auto _ : state) {
// This code gets timed
}
}

正如我们所看到的,对于我指定的范围,设置代码将在此处多次调用。我确实看了一下夹具测试。但我的问题是,是否可以在不使用夹具测试的情况下完成。如果是,那么我们该怎么做?

据我所知,该函数被多次调用,因为benchmark动态决定需要运行多少次基准测试才能获得可靠的结果。如果您不想使用夹具,有多种解决方法。可以使用全局或静态类成员bool来检查是否已调用 setup 函数(不要忘记在 setup 例程运行后设置它(。另一种可能性是使用在其 ctor 中调用设置方法的单例:

class Setup
{
Setup()
{
// call your setup function
std::cout << "singleton ctor called only once in the whole program" << std::endl;
}
public:
static void PerformSetup()
{
static Setup setup;
}
};
static void BM_SomeFunction(benchmark::State& state) {
Setup::PerformSetup()
for (auto _ : state) {
// ...
}
}

但是,夹具使用起来非常简单,并且是为此类用例而设计的。

定义一个继承自benchmark::Fixture的夹具类:

class MyFixture : public benchmark::Fixture
{
public:
// add members as needed
MyFixture()
{
std::cout << "Ctor only called once per fixture testcase hat uses it" << std::endl;
// call whatever setup functions you need in the fixtures ctor 
}
};

然后使用BENCHMARK_F宏在测试中使用您的夹具。

BENCHMARK_F(MyFixture, TestcaseName)(benchmark::State& state)
{
std::cout << "Benchmark function called more than once" << std::endl;
for (auto _ : state)
{
//run your benchmark
}
}

但是,如果您在多个基准测试中使用夹具,ctor 将被多次调用。如果您确实需要在整个基准测试期间仅调用一次某个设置函数,则可以使用单例或static bool来解决此问题,如前所述。也许benchmark也有一个内置的解决方案,但我不知道。


单例的替代品

如果你不喜欢单例类,你也可以使用这样的全局函数:

void Setup()
{
static bool callSetup = true;
if (callSetup)
{
// Call your setup function
}
callSetup = false;
}

问候