Microbenchmark
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
Jetpack Microbenchmark ライブラリを使用すると、Android Studio 内から Android ネイティブ コード(Kotlin または Java)のベンチマークを実行できます。ライブラリはウォームアップを処理し、コードのパフォーマンスと割り当てを測定して、ベンチマーク結果を Android Studio コンソールと JSON ファイルの両方に詳細情報とともに出力します。
ベンチマークを作成する前に、コードをプロファイリングすることをおすすめします。これにより、最適化が必要な、費用の高いオペレーションを見つけることができます。また、実行中に動作の内容を表示して、処理が遅くなる理由を明らかにすることもできます。たとえば、優先度の低いスレッドでの実行、ディスクへのアクセスによるスリープ、ビットマップのデコードなどコストの高い関数の予期せぬ呼び出しなどがあります。
マイクロベンチマークは、アプリ内で何度も実行される CPU 処理(ホットなコードパスとも呼ばれます)の測定に大変役立ちます。たとえば、一度に 1 つの項目を表示する RecyclerView
スクロール、データの変換 / 処理、繰り返し使用されるコードなどがその良い例です。
その他のタイプのコードを Microbenchmark ライブラリで測定するのは困難です。ベンチマークはループ実行されるため、頻繁に実行されないコードや、呼び出されるたびに実行方法が変化するコードの場合、ベンチマークに適していません。
継続的インテグレーション(CI)環境でこのライブラリを使用する方法については、継続的インテグレーションでベンチマークを実行するをご覧ください。
キャッシュの測定を回避する
キャッシュのみを測定しないように注意してください。たとえば、カスタムビューのレイアウトのベンチマークを行うと、レイアウト キャッシュのパフォーマンスのみが測定される可能性があります。これを回避するには、ループごとに異なるレイアウト パラメータを渡します。ただし、ファイル システムのパフォーマンスを測定するケースなどでは、ループ中に OS がファイル システムのキャッシュを保存するため、この回避策も難しい場合があります。
一貫性のあるベンチマークを取得する
モバイル デバイスのクロックは、High 状態(高パフォーマンス時)から Low 状態(節電時やデバイス高温時)へと動的に変化します。このようなクロックの変化によって、ベンチマークの数値が大きく変化することがあります。そのため、ライブラリにはこの問題に対処する方法が用意されています。
クロックをロックする(ユーザーに root 権限のあるデバイスが必要)
安定したパフォーマンスを得るには、クロックをロックすることをおすすめします。これにより、デバイスが熱くなるほどクロックの High 状態が続いたり、ベンチマークが CPU をフルに活用していないときにクロックが Low 状態になったりすることがなくなります。Gradle タスク(gradlew lockClocks
)で適用することも、CI で手動で適用することもできます。この方法は、安定したパフォーマンスを確保するうえでは最善の方法ですが、root 権限を持つ Android デバイスが必要になるため、ほとんどのデバイスでサポートされていません。
Window.setSustainedPerformanceMode()
は、最大 CPU 周波数を抑えるようにアプリレベルで選択できるデバイスでサポートされています。Microbenchmark ライブラリは、この機能がサポートされているデバイス上で実行されると、この API と独自のアクティビティ起動を組み合わせて使用することで、サーマル スロットリングを防ぐとともにベンチマーク結果を安定させます。
この機能は、Android Gradle プラグインが設定する testInstrumentationRunner
によって、デフォルトで有効になります。カスタム ランナーを使用する場合は、AndroidBenchmarkRunner
をサブクラス化して、testInstrumentationRunner
として使用できます。
ランナーは、非透過的なフルスクリーン アクティビティを起動して、ベンチマークがフォアグラウンドで実行される状態にし、他のアプリは描画しません。
自動実行の一時停止
クロックロックとパフォーマンス維持モードのいずれも使用しない場合、ライブラリは、自動サーマル スロットリング検出を行います。有効にすると、内部ベンチマークが定期的に実行され、CPU のパフォーマンスを低下させるほどデバイスの温度が高くなっていないか判定します。CPU パフォーマンスの低下が検出されると、ライブラリは実行を一時停止し、デバイスが冷却した後で、現在のベンチマークを再試行します。
AOT コンパイル
複雑なマイクロベンチマークは安定し、
検出が非常に困難です。測定の一貫性とスピード
反復速度が最優先事項であるため、androidx.benchmark
プラグインは完全に
以下と同様に、デフォルトで microbenchmark APK をコンパイルします。
Macrobenchmark の CompilationMode.Full
。この動作にはベンチマークが必要です
1.3.0-beta01+
、Android Gradle プラグイン 8.4.0+
。この通知を受け取らないように
androidx.benchmark.forceaotcompilation=false
を
gradle.properties
ファイル。
サンプル
GitHub リポジトリにある次のサンプルをご覧ください。
参考情報
フィードバックを送信
ベンチマークの使用に関して問題の報告や機能リクエストの送信を行う場合は、公開されている Issue Tracker をご利用ください。
あなたへのおすすめ
このページのコンテンツやコードサンプルは、コンテンツ ライセンスに記載のライセンスに従います。Java および OpenJDK は Oracle および関連会社の商標または登録商標です。
最終更新日 2025-07-27 UTC。
[[["わかりやすい","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 UTC。"],[],[],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)"]]