谷歌基准自定义设置和拆卸方法
Google Benchmark Custom Setup And Teardown Method
我正在使用基准库来对一些代码进行基准测试。我想在调用实际基准代码一次之前调用一个设置方法,而不是每次都重复,用于多次基准测试方法调用。例如:
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;
}
问候
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- Poco 库 PUT 方法未按预期工作,尽管主机、方法、内容类型设置正确
- 如何在Visual Studio 2017上将类方法设置为参数并将它们与lambda一起使用?
- 将类方法设置为 OpenSSL 回调
- 哪个是设置位的最佳方法以及为什么?
- 设置窗口几何图形特性的正确方法
- 有没有一种方法可以在不设置精度的情况下设置小数位数
- 只设置一次方法中变量的值
- 将类方法设置为外部定义的函数
- 我如何调用我的3个数据成员中每个人的设置方法,然后显示由我的设置方法设置的值
- 使用其公共方法C 设置类的私人属性
- 位掩码:通过集合方法设置对象的不同状态
- 通过对象的指针数组分配内存,并使用方法设置它们的名称
- 设置为实例的静态值在从静态方法设置时有效,但不能从类内的静态方法设置
- 如何为静态模板方法设置别名
- 在qt单元测试中是否可以用单独的方法设置测试数据?
- 如何使用类方法设置单个类数组元素
- 使用私有方法设置类变量
- gdb-python编程:如何编写代码,为C++类的每个方法设置断点
- 从派生类方法设置基对象