[QT] QT test - Writing a Benchmark
http://doc.qt.io/qt-5/qttestlib-tutorial5-example.html
如何写benchmark。
在最后一章中,我们将演示如何使用Qt Test编写基准测试 (benchmark)。
Writing a Benchmark
为了创建benchmark,我们使用QBENCHMARK macro扩展test function。 然后,benchmark test function通常包含设置代码(setup code)和包含要测量的code的QBENCHMARK macro。 此test function设基准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);
}
}
可以在function开始时进行setup,此时时钟不运行。 在QBENCHMARK macro内的代码将会被测量(measured),并可能重复几次以获得准确的测量结果。
有几个后端(back-ends)可用,可以在command line中选择。
Data Functions
Data function可用于创建比较多个数据输入(data inputs)的benchmarks,例如locale aware compare与standard compare。
void TestBenchmark::multiple_data()
{
QTest::addColumn<bool>("useLocaleCompare");
QTest::newRow("locale aware compare") << true;
QTest::newRow("standard compare") << false;
}
然后,test function使用data来决定要进行benchmark的内容。
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(useLocaleCompare)”开关位于QBENCHMARK macro之外,以避免测量其开销(overhead)。 每个benchmark test function都可以有一个active的QBENCHMARK macro。
External Tools
qtestlib-tools project的一部分提供了用于处理和可视化测试数据(visualizing test data)的工具。 这些工具包括用于比较从测试运行(test runs) 中获得的性能数据(performance data) 和用于生成性能数据的基于Web的图表的实用程序的工具。
有关这些工具的更多信息和简单的图形示例,请参阅qtestlib-tools公告。