c++ - Google Benchmark 自定义设置和拆卸方法
问题描述
我正在使用基准库对一些代码进行基准测试。我想在调用实际基准代码之前调用一个设置方法,而不是每次都重复,用于多个基准方法调用。例如:
static void BM_SomeFunction(benchmark::State& state) {
// Perform setup here
for (auto _ : state) {
// This code gets timed
}
}
正如我们所看到的,设置代码将在我指定的范围内被多次调用。我确实看过夹具测试。但我的问题是它可以在不使用夹具测试的情况下完成。如果是,那么我们该怎么做呢?
解决方案
据我所知,该函数被多次调用,因为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;
}
问候
推荐阅读
- string - 如何检查文本是否包含 Golang 列表中的任何单词?
- excel - 如何在另一个工作表上搜索 2 个值,然后基于该值从与它们返回第一张工作表的同一行返回一个特定单元格?
- microsoft-edge - 最近更新后 Edge 中的 Devtools 无法正常工作
- javascript - 按下另一个div后如何隐藏一个div?
- html - 除非以管理员身份登录,否则 Paypal 表单不会在 Wordpress 中显示
- python - 对模型的良好训练报告了糟糕的结果
- scala - 处理 Spark 数据帧/数据集中的重复数据
- enums - 用于在相同枚举之间转换的 Rust 宏
- wordpress - get_posts 或 wp_query 函数中的 Foreach 问题
- python - 以特定长度python分割字符串和整数