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

Google Benchmark Custom Setup And Teardown Method

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

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

正如我们所见,设置代码将在我指定的范围内多次调用。我确实看过夹具测试。但我的问题是不使用夹具测试就可以完成吗?如果是,那么我们该怎么做呢?

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

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) {
    // ...
  }
}

但是,固定装置使用起来非常简单,并且是为此类用例而设计的。

定义一个夹具 class 继承自 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
    }
}

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


单例的替代

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

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

问候