如何编写基准测试。
在最后一章中,我们将演示如何使用Qt Test编写基准测试。
写一个基准
为了创建基准测试,我们使用QBENCHMARK宏扩展测试函数。基准测试函数通常由设置代码和一个QBENCHMARK宏组成,该宏包含要测量的代码。这个测试函数对QString::localeAwareCompare()进行基准测试。
void TestBenchmark::simple()
{
QString str1 = QLatin1String("This is a test string");
QString str2 = QLatin1String("This is a test string");
QCOMPARE(str1.localeAwareCompare(str2), 0);
QBENCHMARK {
str1.localeAwareCompare(str2);
}
}
设置可以在函数开始时完成,此时时钟没有运行。QBENCHMARK宏中的代码将被度量,并且可能会重复多次以获得准确的度量。
有几个后端可用,可以在命令行上选择。
数据函数
数据函数在创建比较多个数据输入的基准时很有用,例如区域设置比较和标准比较。
void TestBenchmark::multiple_data()
{
QTest::addColumn<bool>("useLocaleCompare");
QTest::newRow("locale aware compare") << true;
QTest::newRow("standard compare") << false;
}
测试函数然后使用这些数据来决定对什么进行基准测试。
void TestBenchmark::multiple()
{
QFETCH(bool, useLocaleCompare);
QString str1 = QLatin1String("This is a test string");
QString str2 = QLatin1String("This is a test string");
int result;
if (useLocaleCompare) {
QBENCHMARK {
result = str1.localeAwareCompare(str2);
}
} else {
QBENCHMARK {
result = (str1 == str2);
}
}
Q_UNUSED(result);
}
if (uselocalcompare)”开关被放置在QBENCHMARK宏之外,以避免测量它的开销。每个基准测试函数可以有一个活动的QBENCHMARK宏。
外部工具
用于处理和可视化测试数据的工具可以作为qtestlib-tools项目的一部分使用。其中包括用于比较从测试运行中获得的性能数据的工具,以及用于生成基于web的性能数据图表的实用程序。
有关这些工具的更多信息和一个简单的绘图示例,请参阅qtestlib-tools公告。