Capítulo 5: Cómo escribir una prueba de rendimiento
En este capítulo se explica cómo escribir pruebas de rendimiento utilizando Qt Test.
Cómo escribir una prueba de rendimiento
Para crear una prueba de rendimiento, ampliamos una función de prueba con una macro QBENCHMARK. Una función de prueba de rendimiento consistirá, por lo general, en código de configuración y una macro QBENCHMARK que contenga el código que se va a medir. Esta función de prueba mide el rendimiento de 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);
}
}La configuración se puede realizar al principio de la función. En este momento, el reloj no está en marcha. Se medirá el código incluido dentro de la macro QBENCHMARK y, posiblemente, se repetirá varias veces para obtener una medición precisa.
Hay varios back-ends disponibles que se pueden seleccionar en la línea de comandos.
Funciones de datos
Las funciones de datos son útiles para crear pruebas de rendimiento que comparen múltiples entradas de datos; por ejemplo, una comparación que tenga en cuenta la configuración regional frente a una comparación estándar.
void TestBenchmark::multiple_data()
{
QTest::addColumn<bool>("useLocaleCompare");
QTest::newRow("locale-aware-compare") << true;
QTest::newRow("standard-compare") << false;
}A continuación, la función de prueba utiliza los datos para determinar qué se va a evaluar.
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);
}El modificador ` if (useLocaleCompare) ` se coloca fuera de la macro `QBENCHMARK` para evitar medir su sobrecarga. Cada función de prueba de rendimiento puede tener una macro `QBENCHMARK` activa.
Compilación del ejecutable
Puedes compilar el ejecutable del caso de prueba utilizando CMake o qmake.
Compilación con CMake
Configura los parámetros de compilación en tu archivo CMakeLists.txt:
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
cmake_minimum_required(VERSION 3.16)
project(tutorial5 LANGUAGES CXX)
find_package(Qt6 REQUIRED COMPONENTS Core Gui Test Widgets)
qt_standard_project_setup()
qt_add_executable(tutorial5
benchmarking.cpp
)
set_target_properties(tutorial5 PROPERTIES
WIN32_EXECUTABLE TRUE
MACOSX_BUNDLE TRUE
)
target_link_libraries(tutorial5 PRIVATE
Qt6::Core
Qt6::Gui
Qt6::Test
Qt6::Widgets
)
install(TARGETS tutorial5
BUNDLE DESTINATION .
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
)
qt_generate_deploy_app_script(
TARGET tutorial5
OUTPUT_SCRIPT deploy_script
NO_UNSUPPORTED_PLATFORM_ERROR
)
install(SCRIPT ${deploy_script})A continuación, desde la línea de comandos, ejecuta « cmake » o utiliza el script de conveniencia « qt-cmake », que se encuentra en « Qt-prefix/<version>/<platform>/bin/qt-cmake »:
<Qt-prefix>/<version>/<platform>/bin/qt-cmake <source-dir> <build-dir> -G NinjaA continuación, ejecuta tu herramienta generadora preferida para compilar el ejecutable. En este caso, utilizamos Ninja:
ninjaCompilación con qmake
Configura los ajustes de compilación en tu archivo « .pro »:
QT += widgets testlib
SOURCES = benchmarking.cpp
# install
target.path = $$[QT_INSTALL_EXAMPLES]/qtestlib/tutorial5
INSTALLS += targetA continuación, ejecuta qmake y, por último, ejecuta make para compilar tu ejecutable:
qmake
makeEjecución del ejecutable
Al ejecutar el ejecutable resultante, deberías obtener la siguiente salida:
********* Start testing of TestBenchmark *********
Config: Using QtTest library %VERSION%, Qt %VERSION%
PASS : TestBenchmark::initTestCase()
PASS : TestBenchmark::simple()
RESULT : TestBenchmark::simple():
0.00030 msecs per iteration (total: 79, iterations: 262144)
PASS : TestBenchmark::multiple(locale-aware-compare)
RESULT : TestBenchmark::multiple():"locale-aware-compare":
0.00029 msecs per iteration (total: 78, iterations: 262144)
.....
PASS : TestBenchmark::series(locale-aware-compare:8001)
RESULT : TestBenchmark::series():"locale-aware-compare:8001":
0.039 msecs per iteration (total: 81, iterations: 2048)
Totals: 15 passed, 0 failed, 0 skipped, 0 blacklisted, 3971ms
********* Finished testing of TestBenchmark *********© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.