Capítulo 5: Como escrever um benchmark
Este capítulo demonstra como escrever benchmarks usando o ` Qt Test`.
Criação de um teste de desempenho
Para criar um teste de desempenho, estendemos uma função de teste com uma macro QBENCHMARK. Uma função de teste de desempenho consistirá, então, tipicamente em código de configuração e uma macro QBENCHMARK que contém o código a ser medido. Esta função de teste avalia o desempenho 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);
}
}A configuração pode ser feita no início da função. Nesse momento, o relógio ainda não está em execução. O código dentro da macro QBENCHMARK será medido e, possivelmente, repetido várias vezes para se obter uma medição precisa.
Vários back-ends estão disponíveis e podem ser selecionados na linha de comando.
Funções de dados
As funções de dados são úteis para criar benchmarks que comparam múltiplas entradas de dados, por exemplo, comparação sensível à localidade versus comparação padrão.
void TestBenchmark::multiple_data()
{
QTest::addColumn<bool>("useLocaleCompare");
QTest::newRow("locale-aware-compare") << true;
QTest::newRow("standard-compare") << false;
}A função de teste, então, usa os dados para determinar o que será avaliado.
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);
}A opção ` if (useLocaleCompare) ` é colocada fora da macro `QBENCHMARK` para evitar a medição de sua sobrecarga. Cada função de teste de benchmark pode ter uma macro `QBENCHMARK` ativa.
Compilando o executável
Você pode compilar o executável do caso de teste usando o CMake ou o qmake.
Compilando com o CMake
Configure suas opções de compilação no arquivo 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})Em seguida, na linha de comando, execute ` cmake ` ou use o script de conveniência ` qt-cmake `, localizado em ` Qt-prefix/<version>/<platform>/bin/qt-cmake`:
<Qt-prefix>/<version>/<platform>/bin/qt-cmake <source-dir> <build-dir> -G NinjaEm seguida, execute sua ferramenta geradora preferida para compilar o executável. Aqui, estamos usando o Ninja:
ninjaCompilação com o qmake
Configure suas opções de compilação no arquivo ` .pro `:
QT += widgets testlib
SOURCES = benchmarking.cpp
# install
target.path = $$[QT_INSTALL_EXAMPLES]/qtestlib/tutorial5
INSTALLS += targetEm seguida, execute ` qmake` e, por fim, execute ` make ` para compilar seu executável:
qmake
makeExecutando o executável
Ao executar o executável resultante, você deverá obter a seguinte saída:
********* 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.