Eseguire il benchmark dei profili di riferimento con la libreria Macrobenchmark
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Ti consigliamo di utilizzare Jetpack Macrobenchmark per testare le prestazioni di un'app quando
i profili di base sono attivati e poi confrontare i risultati con un benchmark
con i profili di base disattivati. Con questo approccio, puoi misurare il tempo di avvio dell'app, sia il tempo di visualizzazione iniziale che quello di visualizzazione completa, o le prestazioni di rendering in fase di runtime per verificare se i frame prodotti possono causare jank.
I macrobenchmark ti consentono di controllare la compilazione pre-misurazione utilizzando l'API
CompilationMode. Utilizza valori CompilationMode diversi per confrontare
il rendimento con stati di compilazione diversi. Il seguente snippet di codice mostra come utilizzare il parametro CompilationMode per misurare il vantaggio dei profili di base:
@RunWith(AndroidJUnit4ClassRunner::class)classColdStartupBenchmark{@get:RulevalbenchmarkRule=MacrobenchmarkRule()// No ahead-of-time (AOT) compilation at all. Represents performance of a// fresh install on a user's device if you don't enable Baseline Profiles—// generally the worst case performance.@TestfunstartupNoCompilation()=startup(CompilationMode.None())// Partial pre-compilation with Baseline Profiles. Represents performance of// a fresh install on a user's device.@TestfunstartupPartialWithBaselineProfiles()=startup(CompilationMode.Partial(baselineProfileMode=BaselineProfileMode.Require))// Partial pre-compilation with some just-in-time (JIT) compilation.// Represents performance after some app usage.@TestfunstartupPartialCompilation()=startup(CompilationMode.Partial(baselineProfileMode=BaselineProfileMode.Disable,warmupIteration=3))// Full pre-compilation. Generally not representative of real user// experience, but can yield more stable performance metrics by removing// noise from JIT compilation within benchmark runs.@TestfunstartupFullCompilation()=startup(CompilationMode.Full())privatefunstartup(compilationMode:CompilationMode)=benchmarkRule.measureRepeated(packageName="com.example.macrobenchmark.target",metrics=listOf(StartupTimingMetric()),compilationMode=compilationMode,iterations=10,startupMode=StartupMode.COLD,setupBlock={pressHome()}){// Waits for the first rendered frame, which represents time to initial display.startActivityAndWait()// Waits for content to be visible, which represents time to fully drawn.device.wait(Until.hasObject(By.res("my-content")),5_000)}}
Nello screenshot seguente puoi vedere i risultati direttamente in Android Studio
per l'app Now in Android sample eseguita su Google Pixel 7. I risultati mostrano che l'avvio dell'app è più veloce quando si utilizzano i profili di base (229 ms) rispetto a quando non viene eseguita la compilazione (324,8 ms).
Figura 1. Risultati di ColdStartupBenchmark
che mostrano il tempo di visualizzazione iniziale per nessuna compilazione (324 ms), compilazione completa
(315 ms), compilazione parziale (312 ms) e profili di base
(229 ms).
L'esempio precedente misura il tempo di attesa per la prima schermata (TTID), ovvero
il tempo impiegato dall'app per produrre il primo frame. Tuttavia, questo non
riflette necessariamente il tempo necessario prima che l'utente possa iniziare a interagire con la tua app.
La metrica Tempo al caricamento completo (TTFD) è più utile per misurare e
ottimizzare i percorsi del codice necessari per avere uno stato dell'app completamente utilizzabile.
Ti consigliamo di ottimizzare sia il TTID che il TTFD, in quanto entrambi sono importanti. Un TTID basso
aiuta l'utente a capire che l'app si sta effettivamente avviando. Mantenere il TTFD
breve è importante per garantire che l'utente possa interagire rapidamente con l'app.
I campioni di contenuti e codice in questa pagina sono soggetti alle licenze descritte nella Licenza per i contenuti. Java e OpenJDK sono marchi o marchi registrati di Oracle e/o delle sue società consociate.
Ultimo aggiornamento 2025-08-27 UTC.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Mancano le informazioni di cui ho bisogno","missingTheInformationINeed","thumb-down"],["Troppo complicato/troppi passaggi","tooComplicatedTooManySteps","thumb-down"],["Obsoleti","outOfDate","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Problema relativo a esempi/codice","samplesCodeIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-08-27 UTC."],[],[],null,["We recommend using [Jetpack Macrobenchmark](/topic/performance/benchmarking/macrobenchmark-overview) to test how an app performs when\nBaseline Profiles are enabled, and then compare those results to a benchmark\nwith Baseline Profiles disabled. With this approach, you can measure app startup\ntime---both time to initial and full display---or runtime rendering\nperformance to see if the frames produced can cause jank.\n\nMacrobenchmarks let you control pre-measurement compilation using the\n[`CompilationMode`](/reference/androidx/benchmark/macro/CompilationMode) API. Use different `CompilationMode` values to compare\nperformance with different compilation states. The following code snippet shows\nhow to use the `CompilationMode` parameter to measure the benefit of Baseline\nProfiles: \n\n```kotlin\n@RunWith(AndroidJUnit4ClassRunner::class)\nclass ColdStartupBenchmark {\n @get:Rule\n val benchmarkRule = MacrobenchmarkRule()\n\n // No ahead-of-time (AOT) compilation at all. Represents performance of a\n // fresh install on a user's device if you don't enable Baseline Profiles---\n // generally the worst case performance.\n @Test\n fun startupNoCompilation() = startup(CompilationMode.None())\n\n // Partial pre-compilation with Baseline Profiles. Represents performance of\n // a fresh install on a user's device.\n @Test\n fun startupPartialWithBaselineProfiles() =\n startup(CompilationMode.Partial(baselineProfileMode = BaselineProfileMode.Require))\n\n // Partial pre-compilation with some just-in-time (JIT) compilation.\n // Represents performance after some app usage.\n @Test\n fun startupPartialCompilation() = startup(\n CompilationMode.Partial(\n baselineProfileMode = BaselineProfileMode.Disable,\n warmupIteration = 3\n )\n )\n\n // Full pre-compilation. Generally not representative of real user\n // experience, but can yield more stable performance metrics by removing\n // noise from JIT compilation within benchmark runs.\n @Test\n fun startupFullCompilation() = startup(CompilationMode.Full())\n\n private fun startup(compilationMode: CompilationMode) = benchmarkRule.measureRepeated(\n packageName = \"com.example.macrobenchmark.target\",\n metrics = listOf(StartupTimingMetric()),\n compilationMode = compilationMode,\n iterations = 10,\n startupMode = StartupMode.COLD,\n setupBlock = {\n pressHome()\n }\n ) {\n // Waits for the first rendered frame, which represents time to initial display.\n startActivityAndWait()\n\n // Waits for content to be visible, which represents time to fully drawn.\n device.wait(Until.hasObject(By.res(\"my-content\")), 5_000)\n }\n}\n```\n| **Caution:** Run the benchmarks on a physical device to measure real world performance. Measuring performance on an Android emulator likely provides incorrect results, because resources are shared with its hosting machine.\n\nIn the following screenshot, you can see the results directly in Android Studio\nfor the [Now in Android sample](https://goo.gle/nia) app ran on Google Pixel 7. The\nresults show that app startup is fastest when using Baseline Profiles\n(**229.0ms** ) in contrast with no compilation (**324.8ms**).\n**Figure 1.** Results of `ColdStartupBenchmark` showing time to initial display for no compilation (324ms), full compilation (315ms), partial compilation (312ms), and Baseline Profiles (229ms). **Tip:** You can also retrieve the results as a JSON file to parse them as part of your CI pipeline. For more information, see [Benchmarking in CI](/topic/performance/benchmarking/benchmarking-in-ci).\n\nWhile the previous example shows app startup results captured with\n[`StartupTimingMetric`](/reference/androidx/benchmark/macro/StartupTimingMetric), there are other important metrics worth considering,\nsuch as [`FrameTimingMetric`](/reference/androidx/benchmark/macro/FrameTimingMetric). For more information about all the types of\nmetrics, see [Capture Macrobenchmark metrics](/topic/performance/benchmarking/macrobenchmark-metrics).\n\nTime to full display\n\nThe previous example measures the [time to initial display](/topic/performance/vitals/launch-time#time-initial) (TTID), which is\nthe time taken by the app to produce its first frame. However, this doesn't\nnecessarily reflect the time until the user can start interacting with your app.\nThe [time to full display](/topic/performance/vitals/launch-time#time-full) (TTFD) metric is more useful in measuring and\noptimizing the code paths necessary to have a fully useable app state.\n\nWe recommend optimizing for both TTID and TTFD, as both are important. A low\nTTID helps the user see that the app is actually launching. Keeping the TTFD\nshort is important to help ensure that the user can interact with the app\nquickly.\n\nFor strategies on reporting when the app UI is fully drawn, see [Improve\nstartup timing accuracy](/topic/performance/benchmarking/macrobenchmark-metrics#startup-accuracy).\n\nRecommended for you\n\n- Note: link text is displayed when JavaScript is off\n- \\[Write a Macrobenchmark\\]\\[11\\]\n- \\[Capture Macrobenchmark metrics\\]\\[12\\]\n- \\[App startup analysis and optimization {:#app-startup-analysis-optimization}\\]\\[13\\]"]]