Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

Utilizzo dei profiler C++

Per ottimizzare le prestazioni di Godot, bisogna sapere prima cosa ottimizzare. A tal fine, i profiler sono strumenti utili.

Nota

Nell'editor è disponibile un profiler integrato per GDScript, ma un profiler C++ può essere utile nei casi in cui il profiler di GDScript non sia preciso abbastanza o manchi di informazioni a causa di bug.

Esistono due tipi principali di profiler: i profiler a campionamento e i profiler a tracciamento.

I profiler di campionamento interrompono periodicamente l'esecuzione del programma e prelevano un "campione", che registra quali funzioni sono in esecuzione. Tramite queste informazioni, il profiler stima in quali funzioni il programma ha impiegato la maggior parte del tempo.

I profiler di tracciamento funzionano registrando eventi specifici dell'applicazione (come l'inizio e la fine di un singolo frame), producendo un log chiamato "traccia". Il profiler può utilizzare la traccia per generare un grafico che mostra una cronologia accurata e di alto livello di ciò che è accaduto. Tuttavia, qualsiasi codice non esplicitamente strumentato non apparirà nella cronologia di un profiler di tracciamento!

Godot supporta sia i profiler di campionamento sia i profiler di tracciamento e include già codice per registrare gli eventi più comuni in Godot, per l'uso con un profiler di tracciamento!

Alcuni problemi possono essere più facili da risolvere con un tipo di profiler rispetto a un altro, ma è difficile fornire regole e istruzioni su quale usare. Provali entrambi e vedi cosa puoi imparare!

Profiler a campionamento

Raccomandiamo i seguenti profiler a campionamento:

Configurazione di Godot

Per ottenere informazioni di profilazione utili, è assolutamente necessario utilizzare una build di Godot che includa i simboli di debug. I binari ufficiali non includono i simboli di debug, poiché questi aumenterebbero considerevolmente le dimensioni del download.

Per ottenere dati di profilazione che corrispondano al meglio all'ambiente di produzione (ma con simboli di debug), si dovrebbero compilare i binari con le opzioni di SCons production=yes debug_symbols=yes.

È possibile eseguire un profiler su build meno ottimizzate (ad esempio target=template_debug senza LTO), ma i risultati saranno naturalmente meno rappresentativi delle condizioni reali.

Avvertimento

Non rimuovere i simboli di debug dai file binari tramite il comando strip dopo la compilazione. Altrimenti, non si otterranno più informazioni di profilazione utili durante l'esecuzione di un profiler.

Benchmarking startup/shutdown times

Se si cerca di ottimizzare le prestazioni di avvio/arresto di Godot, è possibile indicare al profiler di usare l'opzione da riga di comando --quit sul binario di Godot. Questo chiuderà Godot subito dopo l'avvio. L'opzione --quit funziona con --editor, --project-manager e --path <percorso alla cartella del progetto> (che esegue direttamente un progetto).

Vedi anche

Consultare Tutorial sulla riga di comando per ulteriori argomenti di riga di comando supportati da Godot.

Profiler a tracciamento

Attualmente Godot supporta tre profiler a tracciamento:

Nota

Perfetto è il sistema di tracciamento predefinito per Android, quindi i modelli di esportazione precompilati con Perfetto integrato e abilitato sono disponibili nella pagina dei rilasci su GitHub.

Per utilizzare uno dei due, è necessario compilare il motore da sorgente. Se non l'hai mai fatto prima, consulta la documentazione per la piattaforma su cui desideri effettuare una profilazione. Dovrai effettuare gli stessi passaggi anche qui, ma con alcuni argomenti in più per scons.

Microbenchmarks

While not technically profiling, microbenchmarks are a related concept: after you've identified your hotspot, you'll want a simple and isolatable way to test whether what you're doing has an impact. While re-profiling can be an option, sometimes a microbenchmark can be simpler.

You can see example benchmark setups in the subsections below. Between C++ and GDScript, GDScript benchmarks are usually the more appropriate choice. Because they involve the GDScript language and its overhead, GDScript benchmarks are truthful to how most people will experience your changes. C++ benchmarks are more versatile and can measure smaller performance differences. However, they are also more difficult to get right. In practice, it can often be good to benchmark both.

Nota

To benchmark effectively can be difficult. Benchmarks can easily lead you astray, for example by not representing the situation faithfully, by failing to account for compiler optimizations and other nuances, or by measuring in an unreliable way such that you record noise instead of an actual performance change. Before you start benchmarking, please read up on benchmarking guides and best practices. A good place to start is Gregg's "Active Benchmarking", which provides a high level overview and quick checklist for benchmarking.

GDScript benchmarks

To run a GDScript benchmark, start by creating a benchmark.gd file with the following contents:

extends SceneTree

func _init():
    const N = 1_000_000

    var t0 := Time.get_ticks_usec()
    for i in N:
        pass  # Do the thing you want to benchmark here.
    var t1 := Time.get_ticks_usec()

    var ns_per_op := (t1 - t0) * 1000.0 / N
    print("Benchmark result: %.1f ns/op" % ns_per_op)
    quit()

Edit the file to add your benchmark. You can run the benchmark using godot --headless -s benchmark.gd.

Nota

At the time of writing, GDScript performs few code optimization. Dead code elimination, for example, is generally not performed. Therefore, it is easier to write a decently representative benchmark in GDScript than in C++. This might change in the future.

C++ benchmarks

To run a C++ benchmark, create the file tests/core/test_user_bench.cpp with the following contents:

#include "tests/test_macros.h"

TEST_FORCE_LINK(test_user_bench)

#include <chrono>
#include <cstdio>

static void user_bench() {
    const int N = 1'000'000;
    static uintptr_t sink = 0; // Defeats dead-code elimination.

    auto t0 = std::chrono::steady_clock::now();
    for (int i = 0; i < N; i++) {
        // Do the thing you want to benchmark here.
        // sink += (uintptr_t)something; // Update the sink from the result somehow.
    }
    auto t1 = std::chrono::steady_clock::now();

    double ns_per_op = std::chrono::duration<double, std::nano>(t1 - t0).count() / N;
    printf("Benchmark result: %.1f ns/op (sink %zu)\n", ns_per_op, (size_t)sink);
}

REGISTER_TEST_COMMAND("user-bench", &user_bench)

Edit the file to add your benchmark. Compile Godot with tests=yes, and run the benchmark using godot --test user-bench.

Nota

C++ benchmarks can be fickle and can easily lead you astray unless you have a strong foundation of knowledge about C++ and compilers. Before you start benchmarking, read up on guides and best practices about how to benchmark C++. You can find free in-depth guides in Bakhvalov's "Performance Analysis and Tuning on Modern CPUs", and Agner Fog's "Software Optimization Resources".