In questa pagina

Capitolo 5: Creazione di un benchmark

Questo capitolo illustra come scrivere benchmark utilizzando Qt Test.

Creazione di un benchmark

Per creare un benchmark, estendiamo una funzione di test con una macro QBENCHMARK. Una funzione di test di benchmark sarà quindi tipicamente costituita da codice di configurazione e da una macro QBENCHMARK che contiene il codice da misurare. Questa funzione di test esegue il benchmark di 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 configurazione può essere effettuata all’inizio della funzione. A questo punto, il timer non è ancora in esecuzione. Il codice all’interno della macro QBENCHMARK verrà misurato ed eventualmente ripetuto più volte al fine di ottenere una misurazione accurata.

Sono disponibili diversi back-end, selezionabili dalla riga di comando.

Funzioni sui dati

Le funzioni dati sono utili per creare benchmark che mettono a confronto più input di dati, ad esempio un confronto che tiene conto delle impostazioni locali rispetto a un confronto standard.

void TestBenchmark::multiple_data()
{
    QTest::addColumn<bool>("useLocaleCompare");
    QTest::newRow("locale-aware-compare") << true;
    QTest::newRow("standard-compare") << false;
}

La funzione di test utilizza quindi i dati per determinare cosa sottoporre al 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);
}

L'opzione if (useLocaleCompare) viene inserita all'esterno della macro QBENCHMARK per evitare di misurarne l'overhead. Ogni funzione di test di benchmark può avere una sola macro QBENCHMARK attiva.

Compilazione dell’eseguibile

È possibile compilare l’eseguibile del caso di test utilizzando CMake o qmake.

Compilazione con CMake

Configurare le impostazioni di compilazione nel file 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})

Successivamente, dalla riga di comando, eseguire cmake oppure utilizzare lo script di convenienza qt-cmake che si trova in Qt-prefix/<version>/<platform>/bin/qt-cmake:

<Qt-prefix>/<version>/<platform>/bin/qt-cmake <source-dir> <build-dir> -G Ninja

Quindi, eseguire lo strumento di generazione preferito per compilare l’eseguibile. In questo caso, utilizziamo Ninja:

ninja

Compilazione con qmake

Configurare le impostazioni di compilazione nel file .pro:

QT += widgets testlib

SOURCES = benchmarking.cpp

# install
target.path = $$[QT_INSTALL_EXAMPLES]/qtestlib/tutorial5
INSTALLS += target

Successivamente, esegui qmake e, infine, esegui make per compilare il tuo eseguibile:

qmake
make

Esecuzione dell’eseguibile

L'esecuzione del file eseguibile risultante dovrebbe fornire il seguente output:

********* 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.