- Benchmark app code
- Quickstart
- Kotlin
- Java
- What to benchmark
- Caching
- Infrequently-run code
- Full project setup
- Set Android Studio properties
- Create a new module
- Write a benchmark
- Kotlin
- Java
- Kotlin
- Java
- Run the benchmark
- Collect the data
- Clock stability
- Lock clocks (requires root)
- Sustained performance mode
- Automatic execution pausing
- Warnings
- Benchmarking samples
- Provide feedback
- Quickstart
Benchmark app code
The Jetpack Benchmark library allows you to quickly benchmark your Kotlin-basedor Java-based code from within Android Studio. The library handles warmup,measures your code performance, and outputs benchmarking results to the AndroidStudio console.
Use cases include scrolling a RecyclerView
, inflating a non-trivial View
hierarchy, and performing database queries.
If you haven't yet adopted AndroidX in a project you want to benchmark, seeMigrate an existing project using Android Studio.
Quickstart
This section provides a quick set of steps to try out benchmarking withoutrequiring you to move code into modules. Because the steps involvedisabling debugging for accurate performance results, you won't committhe changes to your source control system, but it can still be helpful when youwant to run one-off measurements.
To quickly perform one-off benchmarking, do the following:
- Add the library to your module’s
build.gradle
file:
project_root/module_dir/build.gradle
- dependencies {
- androidTestImplementation "androidx.benchmark:benchmark:1.0.0-alpha01"
- }
- To disable debugging in the test manifest, update your
<application>
element to force-disable debugging temporarily as follows:
project_root/module_dir/src/androidTest/AndroidManifest.xml
<!-- Important: disable debuggable for accurate performance results -->
<application
android:debuggable="false"
tools:ignore="HardcodedDebugMode"
tools:replace="android:debuggable"/>
- To add your benchmark, add an instance of
BenchmarkRule
in a testfile in theandroidTest
directory. For more information on writingbenchmarks, see Write a benchmark.
The following code snippet shows how to add a benchmark to a JUnit test:
Kotlin
- @RunWith(AndroidJUnit4::class)
class MyBenchmark {
@get:Rule
val benchmarkRule = BenchmarkRule()@Test
fun benchmarkSomeWork() = benchmarkRule.measureRepeated {
doSomeWork()
}
}
Java
- @RunWith(AndroidJUnit4.class)
class MyBenchmark {
@Rule
public BenchmarkRule benchmarkRule = new BenchmarkRule();@Test
public void myBenchmark() {
final BenchmarkState state = benchmarkRule.getState();
while (state.keepRunning()) {
doSomeWork();
}
}
}
What to benchmark
Benchmarks are most useful for CPU work that is run many times in your app. Goodexamples are RecyclerView
scrolling, data conversions/processing, and piecesof code that get used repeatedly.
Other types of code are more difficult to measure with benchmarking. Becausebenchmarks run in a loop, any code that isn't run frequently, or performsdifferently when called multiple times, may not be a good fit for benchmarking.
Caching
Try to avoid measuring just the cache. For example, a custom view'slayout benchmark might measure only the performance of the layout cache. Toavoid this, you can pass different layout parameters in each loop. In othercases, such as when measuring file system performance, this may be difficultbecause the OS caches the file system while in a loop.
Infrequently-run code
Code that's run once during application startup is not very likely to get JITcompiled by Android Runtime (ART). Because of that, benchmarking this code as itruns in a loop isn't a realistic way to measure its performance.
For this sort of code, we recommend tracing or profiling the code inyour app, instead. Note that this doesn't mean you can't benchmark code inyour startup path, but rather that you should pick code that's run in a loop,and that is likely to get JIT compiled.
Full project setup
To set up benchmarking for regular benchmarking rather than one-offbenchmarking, you isolate benchmarks into their own module. This ensures thattheir configuration, such as setting debuggable
to false
, is separatefrom regular tests.
To do this, you need to complete these tasks:
Place code and resources you want to benchmark into a library module if theyaren't already in one.
Add a new library module to hold the benchmarks themselves.
Our samples give examples of how to set up a project in this way.
Set Android Studio properties
Jetpack Benchmark library is currently in Alpha, and requires manuallysetting Android Studio properties to enable benchmark module wizard support.
To enable the Android Studio template for benchmarking, do the following:
Download Android Studio 3.5 Beta 1 or newer.
In Android Studio, click Help > Edit Custom Properties.
Add the following line to the file that opens:
npw.benchmark.template.module=true
Save and close the file.
Restart Android Studio.
Create a new module
The benchmarking module template automatically configures settings forbenchmarking.
To use the module template to create a new module, do the following:
Right-click your project or module and select New > Module.
Select Benchmark Module and click Next.
Figure 1. Benchmark module
- Enter a module name, choose the language, and click Finish.
A module is created that is pre-configured for benchmarking, with a benchmark directory added and debuggable
set to false
.
Note: debuggable=false
prevents using the debugger and profiling toolswith your tests. Using a separate library module eliminates this drawback.
Write a benchmark
Benchmarks are standard instrumentation tests. To create a benchmark, use theBenchmarkRule
class provided by the library. To benchmark activities, useActivityTestRule
or ActivityScenarioRule
. To benchmark UI code,use @UiThreadTest
.
The following code shows a sample benchmark:
Kotlin
- @RunWith(AndroidJUnit4::class)
class ViewBenchmark {
@get:Rule
val benchmarkRule = BenchmarkRule()@Test
fun simpleViewInflate() {
val context = ApplicationProvider.getApplicationContext<context>()
val inflater = LayoutInflater.from(context)
val root = FrameLayout(context)
benchmarkRule.keepRunning {
inflater.inflate(R.layout.test_simple_view, root, false)
}
}
}
Java
- @RunWith(AndroidJUnit4::class)
public class ViewBenchmark {
@Rule
public BenchmarkRule benchmarkRule = new BenchmarkRule();@Test
public void simpleViewInflate() {
Context context = ApplicationProvider.getApplicationContext<context>();
final BenchmarkState state = benchmarkRule.getState();
LayoutInflater inflater = LayoutInflater.from(context);
FrameLayout root = new FrameLayout(context);
while (state.keepRunning()) {
inflater.inflate(R.layout.test_simple_view, root, false);
}
}
}
You can disable timing for sections of code you don't want to measure, as shownin the following code sample:
Kotlin
- @Test
fun bitmapProcessing() = benchmarkRule.measureRepeated {
val input: Bitmap = runWithTimingDisabled { constructTestBitmap() }
processBitmap(input)
}
Java
- @Test
public void bitmapProcessing() {
final BenchmarkState state = benchmarkRule.getState();
while (state.keepRunning()) {
state.pauseTiming();
Bitmap input = constructTestBitmap();
state.resumeTiming();processBitmap(input);
}
}
For information on running the benchmark, seeRun the benchmark.
Run the benchmark
In Android Studio, the benchmark will run when you run your app. On AndroidStudio 3.4 and higher, you can see output sent to the console.
To run the benchmark, in the module, navigate to benchmark/src/androidTest
andpress Control
+Shift
+F10
(Command
+Shift
+R
on Mac). Results of thebenchmark appear in the console, as shown in Figure 2:
Figure 2. Benchmarking output in Android Studio
From the command line, run the regular connectedCheck
:
./gradlew benchmark:connectedCheck
Collect the data
In addition to sending output to the console in Android Studio, the benchmarkresults are written to disk in both JSON and XML formats. These are written tothe external shared downloads folder on the device (usually at/storage/emulated/0/Download/<app_id>-benchmarkData.<extension>
) and on thehost at<project_root>/<module>/build/benchmark_reports/<app_id>-benchmarkData.<extension>
.
Note: For results to be copied to the host when benchmarks are complete, youmust have configured the androidx.benchmark
Gradle plugin, as covered inLock clocks (requires root).
Clock stability
Clocks on mobile devices dynamically change from high state (for performance)to low state (to save power, or when the device gets hot). These varying clockscan make your benchmark numbers vary widely, so the library provides ways todeal with this issue.
Lock clocks (requires root)
Locking clocks is the best way to get stable performance. It ensures that clocksnever get high enough to heat up the device, or low if a benchmark isn't fullyutilizing the CPU. While this is the best way to ensure stable performance, itisn't supported on most devices, due to requiring adb
root.
To lock your clocks, add the supplied helper plugin to the top level project’sclasspath in the main build.gradle
file:
buildscript {
...
dependencies {
...
classpath "androidx.benchmark:benchmark-gradle-plugin:1.0.0-alpha01"
}
}
Apply the plugin in the build.gradle
of the module you are benchmarking:
apply plugin: com.android.app
apply plugin: androidx.benchmark
...
This adds benchmarking Gradle tasks to your project, including./gradlew lockClocks
and ./gradlew unlockClocks
. Use these tasks to lock andunlock a device’s CPU using adb.
If you have multiple devices visible to adb, use the environment variableANDROID_SERIAL
to specify which device the Gradle task should operate on:
- ANDROID_SERIAL=device-id-from-adb-devices ./gradlew lockClocks
Note: Rebooting resets your device clocks.
Sustained performance mode
Window.setSustainedPerformanceMode()
) is a feature supported by somedevices that enables an app to opt for a lower max CPU frequency. When runningon supported devices, the Benchmark library uses a combination of this API andlaunching its own activity to both prevent thermal throttling and stabilizeresults.
This functionality is already enabled in modules created using the benchmarkmodule template. To enable this functionality in other modules, add theinstrumentation runner provided by the library to your benchmark module'sbuild.gradle
file:
project_root/benchmark/build.gradle
- android {
- defaultConfig {
- testInstrumentationRunner "androidx.benchmark.AndroidBenchmarkRunner"
- }
- }
The runner launches an opaque, fullscreen activity to ensure that the benchmarkruns in the foreground and without any other app drawing.
Automatic execution pausing
If neither clock-locking nor sustained performance are used, the libraryperforms automatic thermal throttling detection. When enabled, the internalbenchmark periodically runs to determine when the device temperature has gottenhigh enough to lower CPU performance. When lowered CPU performance is detected,the library pauses execution to let the device cool down, and retries thecurrent benchmark.
Warnings
The library detects the following conditions to ensure your project andenvironment are set up for release-accurate performance:
Debuggable
is set tofalse
.- A physical device, not an emulator, is being used.
- Clocks are locked if the device is rooted.
If any of the above checks fails, test names are intentionally corrupted whenreporting results by prepending "DEBUGGABLE_
." This is done to discourage useof inaccurate measurements.
Benchmarking samples
Sample benchmark code is available in the following projects:
- https://github.com/googlesamples/android-performance
https://github.com/googlesamples/android-architecture-components
The sample projects include:BenchmarkSample: this is a standalone sample, which shows how touse a benchmark module to measure code and UI.
PagingWithNetworkSample: Android Architecture Components sample,which shows how to benchmark
RecyclerView
performance.WorkManagerSample: Android Architecture Components sample, whichshows how to benchmark
WorkManager
workers.
Provide feedback
To report issues or submit feature requests when using benchmarking, see thepublic issue tracker.