Microbenchmark
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
運用 Jetpack Microbenchmark 程式庫,您可以在 Android Studio 中,為 Android 原生程式碼 (Kotlin 或 Java) 執行基準測試。這個程式庫可處理暖機程序、評估程式碼效能和配置次數,並將基準測試結果輸出至 Android Studio 主控台和包含更多詳情的 JSON 檔案。
建議您先剖析程式碼,再編寫基準測試。這樣一來,您可以找出耗用較多資源且值得最佳化的作業,並查看作業執行期間的活動,瞭解作業緩慢的原因,例如在低優先順序的執行緒上執行、因存取磁碟而進入休眠狀態,或意外呼叫會耗用大量資源的函式 (例如點陣圖解碼)。
Microbenchmark 最適合用於在應用程式中多次執行的 CPU 作業,也稱為「熱程式碼路徑」。典型例子包括捲動時會一次顯示一個項目的 RecyclerView
、資料轉換或處理,以及其他會重複使用的程式碼片段。
Microbenchmark 程式庫較難用於評估其他類型的程式碼。由於基準測試會以迴圈方式執行,因此如果程式碼不常執行,或多次呼叫時會以不同方式執行,都可能不適合執行基準測試。
如要瞭解如何在持續整合 (CI) 環境中使用此程式庫,請參閱「在持續整合中執行基準測試」。
避免測量快取
請避免只測量快取。舉例來說,自訂資料檢視的版面配置基準只能測量版面配置快取的成效。為避免這種情況,您可以在每個迴圈中傳遞不同的版面配置參數。在其他情況下,例如評估檔案系統效能時,由於 OS 會在迴圈中快取檔案系統,因此可能難以評估。
取得一致的基準
在節省電力或裝置過熱時,為了確保效能,行動裝置上的時鐘功能會動態調整,從高狀態變為低狀態。不同的時鐘可能導致基準測試數據相差甚遠,因此程式庫提供處理此問題的方法。
鎖定時鐘 (必須啟用已解鎖裝置)
鎖定時鐘是取得穩定效能的最佳方式,可確保不會因時鐘頻率過高導致裝置過熱,也不會因基準測試未充分運用 CPU 而導致頻率過低。可透過 Gradle 工作套用
(gradlew lockClocks
) 或在 CI 中手動執行。雖然這個方式
可協助確保效能穩定,但由於部分裝置不支援
需要使用已啟用 Root 權限的 Android 裝置
Window.setSustainedPerformanceMode()
是裝置支援的功能,可讓應用程式選擇較低的 CPU 頻率上限。當 Microbenchmark 程式庫在支援的裝置上執行時,就會使用此 API 的組合,並啟動本身的活動,既能防止出現過熱保護,又能取得穩定結果。
根據預設,這項功能是由 Android Gradle 外掛程式設定的 testInstrumentationRunner
啟用。如果想使用自訂執行器,則可將 AndroidBenchmarkRunner
設為子類別,並用做 testInstrumentationRunner
。
執行器會啟動不透明的全螢幕活動,確保基準測試在前景執行,且系統未在繪製其他應用程式。
自動暫停執行
如未鎖定時鐘或使用持續效能模式,程式庫會自動執行過熱保護偵測功能。啟用這項功能後,系統會定期執行內部基準測試,判斷裝置溫度是否達到會降低 CPU 效能的程度。偵測到 CPU 效能下降時,程式庫會暫停執行,讓裝置降溫,然後重試當前的基準測試。
AOT 編譯
複雜的 Microbenchmark 需要較長時間才能穩定運作,
變得不穩定以一致的評估方式
疊代速度是首要之務,androidx.benchmark
外掛程式
根據預設,系統會編譯您的 Microbenchmark APK,類似於
CompilationMode.Full
(位於 Macrobenchmark 中)。這項行為需要基準測試
1.3.0-beta01+
和 Android Gradle 外掛程式 8.4.0+
。如果不想使用這個
在您的應用程式中設定 androidx.benchmark.forceaotcompilation=false
gradle.properties
檔案。
範例
請查看 GitHub 存放區中的以下範例:
其他資源
提供意見
使用基準測試時,如要回報問題或提交功能要求,請前往公開的 Issue Tracker。
為您推薦
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-07-27 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-07-27 (世界標準時間)。"],[],[],null,["# Microbenchmark\n\nThe Jetpack Microbenchmark library lets you benchmark your Android native\ncode---Kotlin or Java---from within Android Studio. The library handles warmup,\nmeasures your code performance and allocation counts, and outputs benchmarking\nresults to both the [Android Studio console](/studio/profile/microbenchmark-write#benchmark-results) and a [JSON file](/studio/profile/benchmarking-in-ci#benchmark-data-example) with more\ndetail.\n\nWe recommend you [profile your code](/studio/profile) before writing a benchmark. This helps\nyou find expensive operations that are worth optimizing. It can also show why\nthe operations are slow by showing what is happening while they run, such as\nrunning on a low-priority thread, sleeping due to disk access, or unexpectedly\ncalling into an expensive function, like bitmap decoding.\n\nMicrobenchmarks are most useful for CPU work that is run many times in your app,\nalso known as *hot code paths* . Good examples are `RecyclerView` scrolling with\none item shown at a time, data conversions or processing, and other pieces of\ncode that get used repeatedly.\n\nOther types of code are more difficult to measure with the Microbenchmark\nlibrary. Because benchmarks run in a loop, any code that isn't run frequently or\nperforms differently when called multiple times might not be a good fit for\nbenchmarking.\n\nTo learn how to use the library in a Continuous Integration (CI) environment,\nsee [Run benchmarks in Continuous Integration](/studio/profile/benchmarking-in-ci).\n\nAvoid measuring cache\n---------------------\n\nTry to avoid measuring just the cache. For example, a custom view's layout\nbenchmark might measure only the performance of the layout cache. To avoid this,\nyou can pass different layout parameters in each loop. In other cases, such as\nwhen measuring file system performance, this might be difficult because the OS\ncaches the file system while in a loop.\n\nObtain consistent benchmarks\n----------------------------\n\nClocks on mobile devices dynamically change from high state, for performance, to\nlow state, to save power or when the device gets hot. These varying clocks can\nmake your benchmark numbers vary widely, so the library provides ways to deal\nwith this issue.\n\n### Lock clocks (requires rooted device)\n\nLocking clocks is the best way to get stable performance. It helps ensure that\nclocks never get high enough to heat up the device, or low if a benchmark isn't\nfully utilizing the CPU. It can be applied with a Gradle task\n(`gradlew lockClocks`), or [manually in CI](/studio/profile/benchmarking-in-ci#clock-locking). While this is the best way to\nhelp ensure stable performance, it isn't supported on most devices, due to\nrequiring a rooted Android-powered device.\n\n### Sustained performance mode\n\n[`Window.setSustainedPerformanceMode()`](/reference/android/view/Window#setSustainedPerformanceMode(boolean)) is a feature supported by devices\nthat let an app opt for a lower max CPU frequency. When running on supported\ndevices, the Microbenchmark library uses a combination of this API and launching\nits own activity to both prevent thermal throttling and stabilize results.\n\nThis feature is enabled by default by the [`testInstrumentationRunner`](/training/testing/espresso/setup#set-instrumentation-runner) set\nby the Android Gradle plugin. If you want to use a custom runner, you can\nsubclass the [`AndroidBenchmarkRunner`](/reference/kotlin/androidx/benchmark/junit4/AndroidBenchmarkRunner) and use it as your\n`testInstrumentationRunner`.\n\nThe runner launches an opaque, fullscreen activity to ensure that the benchmark\nruns in the foreground and without any other app drawing.\n\n### Automatic execution pausing\n\nIf you don't use clock-locking or sustained performance, the library performs\nautomatic thermal throttling detection. When enabled, the internal benchmark\nperiodically runs to determine when the device temperature gets high enough to\nlower CPU performance. When it detects lowered CPU performance, the library\npauses execution to let the device cool down and then retries the current\nbenchmark.\n\n### AOT Compilation\n\nComplex microbenchmarks can take a long time to stabilize, and make\nstabilization very difficult to detect. As consistent measurement and fast\niteration speed are top priorities, the `androidx.benchmark` plugin fully\ncompiles your microbenchmark apk by default, similar to\n[`CompilationMode.Full`](/reference/androidx/benchmark/macro/CompilationMode.Full) in Macrobenchmarks. This behavior requires Benchmark\n`1.3.0-beta01+`, and Android Gradle Plugin `8.4.0+`. You can opt out of this\nbehavior by setting `androidx.benchmark.forceaotcompilation=false` in your\n`gradle.properties` file.\n\nSamples\n-------\n\nSee the following samples in the GitHub repository:\n\n- [Performance samples](https://github.com/android/performance-samples)\n- [PagingWithNetworkSample](https://github.com/android/architecture-components-samples/tree/main/PagingWithNetworkSample/benchmark)\n- [WorkManagerSample](https://github.com/android/architecture-components-samples/tree/main/WorkManagerSample/benchmark)\n\nAdditional resources\n--------------------\n\n- [Fighting regressions with Benchmarks in CI](https://medium.com/androiddevelopers/fighting-regressions-with-benchmarks-in-ci-6ea9a14b5c71)\n\nProvide feedback\n----------------\n\nTo report issues or submit feature requests when using benchmarking, see the\n[public issue\ntracker](https://issuetracker.google.com/issues/new?component=585351).\n\nRecommended for you\n-------------------\n\n- Note: link text is displayed when JavaScript is off\n- [Benchmark your app](/topic/performance/benchmarking/benchmarking-overview)\n- [Create Baseline Profiles {:#creating-profile-rules}](/topic/performance/baselineprofiles/create-baselineprofile)\n- [JankStats Library](/topic/performance/jankstats)"]]