首页 > 解决方案 > Google Benchmark 自定义设置和拆卸方法

问题描述

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

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

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

标签: c++benchmarkingmicrobenchmarkgoogle-benchmark

解决方案


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

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。如果您确实需要在整个基准测试期间只调用一次特定的设置函数,您可以使用 Singleton 或 astatic bool来解决此问题,如前所述。也许benchmark也有一个内置的解决方案,但我不知道。


单例的替代品

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

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

问候


推荐阅读