Microbenchmark
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
Jetpack Microbenchmark 라이브러리를 사용하여 Android 스튜디오에서 Android 네이티브 코드(Kotlin 또는 Java)를 벤치마킹할 수 있습니다. 이 라이브러리는 준비 작업을 처리하고 코드 성능과 할당 수를 측정하며 Android 스튜디오 콘솔과 JSON 파일 모두에 자세한 정보가 포함된 벤치마킹 결과를 출력합니다.
벤치마크를 작성하기 전에 코드를 프로파일링하는 것이 좋습니다. 그러면 최적화할 가치가 있는 높은 비용의 작업을 찾는 데 도움이 됩니다. 작업 실행 중에 발생하는 상황을 표시하여 작업이 느린 이유를 노출할 수도 있습니다. 우선순위가 낮은 스레드에서 실행, 디스크 액세스 권한으로 인한 절전 모드, 비용이 많이 드는 함수의 예기치 않은 호출(예: 비트맵 디코딩)이 원인일 수 있습니다.
Microbenchmark는 앱에서 여러 번 실행되는 CPU 작업(핫 코드 경로라고도 함)에 가장 유용합니다. 좋은 예로는 한 번에 항목을 한 개 표시하는 RecyclerView
스크롤, 데이터 변환 또는 처리, 반복적으로 사용되는 다른 코드 조각이 있습니다.
다른 유형의 코드는 Microbenchmark 라이브러리로 측정하기 더 어렵습니다. 벤치마크는 루프에서 실행되기 때문에 자주 실행되지 않거나 여러 번 호출될 때 다르게 실행되는 코드는 벤치마킹에 적합하지 않을 수 있습니다.
지속적 통합(CI) 환경에서 라이브러리를 사용하는 방법을 알아보려면 지속적 통합에서 벤치마크 실행을 참고하세요.
캐시 측정 방지
캐시만 측정하는 것을 피하세요. 예를 들어, 맞춤 뷰의 레이아웃 벤치마크가 레이아웃 캐시의 성능만 측정할 수 있는데, 이러한 상황을 피하려면 각 루프에 서로 다른 레이아웃 매개변수를 전달하면 됩니다. 그러나 파일 시스템 성능을 측정하는 등의 다른 경우에는 OS가 루프에 있는 동안 파일 시스템을 캐시하기 때문에 이것이 어려울 수 있습니다.
일관된 벤치마크 획득
휴대기기의 클록은 높은 상태(성능을 위해)에서 낮은 상태(전원을 절약하기 위해 또는 기기에 열이 발생하는 경우)까지 동적으로 변경됩니다. 이와 같이 변화하는 클록으로 인해 벤치마크 숫자가 크게 달라질 수 있으므로 라이브러리에서 이 문제를 처리하는 방법을 제공합니다.
클록 잠금(루팅된 기기가 필요함)
클록 잠금은 안정적인 성능을 얻는 가장 좋은 방법입니다. 클록을 잠그면 클록이 기기를 과열시킬 만큼 높아지거나 벤치마크가 CPU를 완전히 활용하지 않는 경우 낮아지지 않습니다. Gradle 작업(gradlew lockClocks
)을 사용하여 적용하거나 CI에서 수동으로 적용할 수 있습니다. 클록을 잠그는 것은 안정적인 성능을 보장하는 가장 좋은 방법이지만 루팅된 Android 기기가 필요하기 때문에 대부분의 기기에서 지원되지 않습니다.
Window.setSustainedPerformanceMode()
는 앱에서 더 낮은 최대 CPU 주파수를 선택할 수 있도록 하는 기능이며 기기에서 지원됩니다. 지원되는 기기에서 실행되는 경우 Microbenchmark 라이브러리는 이 API를 사용하는 동시에 자체 활동을 실행하여 열 제한을 방지하고 결과를 안정화합니다.
이 기능은 Android Gradle 플러그인에서 설정된 testInstrumentationRunner
를 통해 기본적으로 사용 설정됩니다. 맞춤 실행기를 사용하려면 AndroidBenchmarkRunner
를 서브클래스로 만들어 testInstrumentationRunner
로 사용할 수 있습니다.
벤치마크가 다른 앱 드로잉 없이 포그라운드에서 실행될 수 있도록 실행기가 불투명한 전체 화면 활동을 시작합니다.
자동 실행 일시중지
클록 잠금 또는 지속적인 성능을 사용하지 않으면 라이브러리에서 자동 열 제한 감지를 실행합니다. 사용 설정된 경우 내부 벤치마크가 주기적으로 실행되어 CPU 성능을 저하할 정도로 기기 온도가 높아진 시기를 확인합니다. CPU 성능 저하가 감지되면 라이브러리가 실행을 일시중지하여 기기의 열을 식히고 현재 벤치마크를 다시 시도합니다.
AOT 컴파일
복잡한 Microbenchmark는 안정화하고
감지하기가 매우 어렵습니다. 일관성 있는 측정과 빠른 속도
반복 속도가 가장 중요하며, 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를 참고하세요.
추천 서비스
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 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)"]]