Chapter 5: Writing a BenchmarkFiles:
In this final chapter we will demonstrate how to write benchmarks using QTestLib. Writing a BenchmarkTo create a benchmark we extend a test function with a QBENCHMARK macro. A benchmark test function will then typically consist of setup code and a QBENCHMARK macro that contains the code to be measured. This test function benchmarks 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); } } Setup can be done at the beginning of the function, the clock is not running at this point. The code inside the QBENCHMARK macro will be measured, and possibly repeated several times in order to get an accurate measurement. Several back-ends are available and can be selected on the command line. Data FunctionsData functions are useful for creating benchmarks that compare multiple data inputs, for example locale aware compare against standard compare. void TestBenchmark::multiple_data() { QTest::addColumn<bool>("useLocaleCompare"); QTest::newRow("locale aware compare") << true; QTest::newRow("standard compare") << false; } The test function then uses the data to determine what to 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); } } } The "if(useLocaleCompare)" switch is placed outside the QBENCHMARK macro to avoid measuring its overhead. Each benchmark test function can have one active QBENCHMARK macro. External ToolsTools for handling and visualizing test data are available as part of the qtestlib-tools project in the Qt Labs web site. These include a tool for comparing performance data obtained from test runs and a utility to generate Web-based graphs of performance data. See the qtestlib-tools announcement for more information on these tools and a simple graphing example. [Previous: Chapter 4] © 2008-2011 Nokia Corporation and/or its subsidiaries. Nokia, Qt and their respective logos are trademarks of Nokia Corporation in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. Privacy Policy Licensees holding valid Qt Commercial licenses may use this document in accordance with the Qt Commercial License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Nokia. Alternatively, this document may be used under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. |