Four moves that take a sluggish first launch to something you can defend with numbers: set up Macrobenchmark, generate the profiles, measure cold start honestly, and let CI keep it that way.
Every Android team eventually meets the same stubborn fact: the first launch after an install or an update feels slower than anything you see in your own debug builds. Your code did not get worse. The runtime simply knows nothing about it yet. ART starts out interpreting your bytecode, the JIT compiles whatever turns out to be hot while the user stares at a splash screen, and a background job fixes the whole thing hours later, when nobody is looking.
Baseline Profiles and Startup Profiles let you hand ART that knowledge in advance. This post walks through the full loop on a small sample app called Tidewatch (package app.tidewatch.android), a tide and wind forecast app with a list of coastal stations and a detail screen. Everything is written in Kotlin, and every section ends with the failure modes that cost me real hours, not hypothetical ones.
The two files do different jobs. A Baseline Profile is a list of classes and methods that ART should compile ahead of time. A Startup Profile is a list of classes that R8 should place together in the primary DEX, so the launch path reads fewer pages from disk. You generate them with the same test, and you can ship either alone. The Startup Profile’s payoff is largest when your app spans more than one DEX file, because that is where deciding what lands in the primary DEX matters most, but class locality can help smaller apps too.
A note on versions before we start. As of November 2026 the Benchmark library line has reached 1.5.0 stable, with 1.6 in alpha, and the Baseline Profile Gradle plugin is released alongside it. The 1.5 line moves Macrobenchmark onto UiAutomator 2.4, and the ArtMetric that can flag JIT activity and unoptimized class loading (handy for validating a profile) has been available since the 1.4 line. Check the AndroidX Benchmark release notes for the current numbers before you copy anything below.
1. Macrobenchmark setup
The shape of the project
You need two modules. The consumer is your app. The producer is an com.android.test module that drives the app on a device, once to record profiles and once to measure startup. The Gradle plugin joins them: it adds extra build types to the app, runs the producer's tests against the right one, and copies the output back into the app's sources.
Create the producer from Android Studio’s “Baseline Profile Generator” module template. It wires up the instrumentation details that are easy to get subtly wrong by hand. Then pin versions in one place:
# gradle/libs.versions.toml [versions] benchmark = "1.5.0" profileinstaller = "1.4.1" # check for a newer release androidxTestExt = "1.2.1" [libraries] androidx-benchmark-macro-junit4 = { module = "androidx.benchmark:benchmark-macro-junit4", version.ref = "benchmark" } androidx-profileinstaller = { module = "androidx.profileinstaller:profileinstaller", version.ref = "profileinstaller" } androidx-test-ext-junit = { module = "androidx.test.ext:junit", version.ref = "androidxTestExt" } [plugins] baselineprofile = { id = "androidx.baselineprofile", version.ref = "benchmark" } The producer module
// baselineprofile/build.gradle.kts import com.android.build.api.dsl.ManagedVirtualDevice plugins { alias(libs.plugins.android.test) alias(libs.plugins.baselineprofile) } android { namespace = "app.tidewatch.android.baselineprofile" compileSdk = 36 defaultConfig { minSdk = 28 targetSdk = 36 testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } targetProjectPath = ":app" testOptions.managedDevices.devices { create<ManagedVirtualDevice>("pixel6Api34") { device = "Pixel 6" apiLevel = 34 systemImageSource = "aosp" // Google-services images block profile capture } } } baselineProfile { managedDevices += "pixel6Api34" useConnectedDevices = false } dependencies { implementation(libs.androidx.test.ext.junit) implementation(libs.androidx.benchmark.macro.junit4) } If you use AGP 9 with its built-in Kotlin support, you can drop the separate Kotlin Android plugin from these files. The 1.5 plugin no longer requires the old DSL opt-out on AGP 9.
The consumer module
// app/build.gradle.kts plugins { alias(libs.plugins.android.application) alias(libs.plugins.baselineprofile) } android { namespace = "app.tidewatch.android" compileSdk = 36 defaultConfig { minSdk = 26 targetSdk = 36 } buildTypes { release { isMinifyEnabled = true isShrinkResources = true proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro", ) } } } baselineProfile { // Uses startup-prof.txt to drive DEX layout. Needs R8 and a recent AGP; set explicitly // even if your AGP version already enables it by default. dexLayoutOptimization = true } dependencies { implementation(libs.androidx.profileinstaller) baselineProfile(project(":baselineprofile")) } profileinstaller matters more than it looks. Play delivers profiles through its own path, but anything installed another way (internal test builds, enterprise distribution, adb install) relies on the library to hand the profile to ART on first run. Even then, compilation is typically queued for the next background dexopt pass rather than done immediately, so a sideloaded build can still start slowly at first.
Make Compose visible to UiAutomator
If your UI is Compose, UiAutomator cannot see test tags until you expose them as resource ids. Do it once at the root:
// Newer Compose releases may not need the opt-in; drop it if the compiler warns it is redundant. // Imports for these snippets: androidx.activity.compose.ReportDrawnWhen, // androidx.compose.ui.semantics.{semantics, testTagsAsResourceId}, androidx.compose.ui.platform.testTag. // ForecastUiState, LoadingIndicator and StationRow are the sample app's own types. @OptIn(ExperimentalComposeUiApi::class) @Composable fun TidewatchRoot(content: @Composable () -> Unit) { Box(Modifier.semantics { testTagsAsResourceId = true }) { content() } } @Composable fun ForecastScreen(state: ForecastUiState, onOpen: (String) -> Unit) { // Tells the system when the screen is genuinely usable (more on this in section 3). ReportDrawnWhen { state is ForecastUiState.Ready } when (state) { ForecastUiState.Loading -> LoadingIndicator() is ForecastUiState.Ready -> LazyColumn(Modifier.testTag("forecast_list")) { items(state.stations, key = { it.id }) { station -> StationRow(station, onClick = { onOpen(station.id) }) } } } } Failure modes in setup
- Wrong device class. Profile generation needs API 33 or newer, or API 28 and up on a rooted device or emulator. A stock emulator image on API 30 fails in confusing ways. The managed device above sidesteps this.
- Google APIs system image. Use the
aospimage. Images that ship with Google services can interfere with capture. - Debuggable measurement builds. Macrobenchmark rejects debuggable apps, and for good reason: a debuggable app runs far slower than release. Measure only the plugin’s
benchmarkReleasevariant, which is minified and profileable. If you wire variants by hand, make sure the app declares<profileable android:shell="true" />and is not debuggable. - Skipping R8. A profile validated against an unminified build tells you little about the shrunk build users actually run. The plugin generates against
nonMinifiedReleaseand R8 maps the rules at build time, but your measurements must run against the minified one.
2. Generating profiles
Journeys first, annotations second
A profile is only as good as the journeys that produced it. Start with a small shared file of UI steps. Both the generator and the benchmark will reuse it, which keeps “what we recorded” and “what we measure” from drifting apart.
// baselineprofile/src/main/kotlin/app/tidewatch/android/baselineprofile/StartupJourneys.kt package app.tidewatch.android.baselineprofile import androidx.benchmark.macro.MacrobenchmarkScope import androidx.test.uiautomator.Direction import androidx.test.uiautomator.By import androidx.test.uiautomator.UiObject2 import androidx.test.uiautomator.Until const val TARGET_PACKAGE = "app.tidewatch.android" private const val WAIT_MS = 10_000L fun MacrobenchmarkScope.launchToForecast() { pressHome() startActivityAndWait() awaitForecast() } fun MacrobenchmarkScope.awaitForecast() { requireTag("forecast_list") } fun MacrobenchmarkScope.scrollForecast() { val list = requireTag("forecast_list") list.setGestureMargin(device.displayWidth / 5) repeat(3) { list.fling(Direction.DOWN) device.waitForIdle() } list.fling(Direction.UP) device.waitForIdle() } fun MacrobenchmarkScope.openFirstStation() { val list = requireTag("forecast_list") // The container can exist a frame before its rows are composed, so wait for a child. val firstRow = list.children.firstOrNull() ?: error("forecast_list has no rows yet; wait for data before opening a station") firstRow.click() requireTag("station_detail") device.pressBack() requireTag("forecast_list") } // Compose test tags surface as bare resource ids, so By.res(tag) is correct here. // For classic Views use By.res(packageName, id) instead. private fun MacrobenchmarkScope.requireTag(tag: String): UiObject2 = device.wait(Until.findObject(By.res(tag)), WAIT_MS) ?: error("Timed out after ${WAIT_MS}ms waiting for '$tag'. A silent miss here ships a hollow profile.") The error(...) is not decoration. device.wait returns null on timeout, and a journey that quietly gives up produces a profile that contains startup code and nothing else. You want that to fail loudly.
The generator
@RunWith(AndroidJUnit4::class) @LargeTest class BaselineProfileGenerator { @get:Rule val rule = BaselineProfileRule() // Only the launch path belongs in the startup profile: it drives DEX layout. @Test fun startupJourney() = rule.collect( packageName = TARGET_PACKAGE, includeInStartupProfile = true, ) { launchToForecast() } // Everything users do in their first minute belongs in the baseline profile. @Test fun criticalJourneys() = rule.collect(packageName = TARGET_PACKAGE) { launchToForecast() scrollForecast() openFirstStation() } } Run it with the plugin’s task:
./gradlew :app:generateReleaseBaselineProfile \ -Pandroid.testoptions.manageddevices.emulator.gpu=swiftshader_indirect The plugin boots the managed device, runs the producer’s tests against nonMinifiedRelease, and writes baseline-prof.txt (and startup-prof.txt if you flagged a journey) into app/src/release/generated/baselineProfiles/. Commit those files. Reviewable text in version control is the whole point.
Prove it landed
Do not trust the build output. Ask ART, from inside the app, whether the profile is actually in effect. ProfileVerifier reports it, and the answer is worth logging to your analytics so you learn what fraction of real users have a compiled profile:
object ProfileStatusReporter { suspend fun report(sink: (String) -> Unit) { // await() comes from kotlinx-coroutines-guava; it keeps the call cancellable and // avoids parking an IO thread on a blocking Future.get(). val status = ProfileVerifier.getCompilationStatusAsync().await() sink( when (status.profileInstallResultCode) { ProfileVerifier.CompilationStatus.RESULT_CODE_COMPILED_WITH_PROFILE -> "compiled_with_profile" ProfileVerifier.CompilationStatus.RESULT_CODE_PROFILE_ENQUEUED_FOR_COMPILATION -> "enqueued" ProfileVerifier.CompilationStatus.RESULT_CODE_COMPILED_WITH_PROFILE_NON_MATCHING -> "compiled_non_matching" ProfileVerifier.CompilationStatus.RESULT_CODE_NO_PROFILE -> "no_profile" else -> "other_${status.profileInstallResultCode}" } ) } } // In MainActivity.onCreate, off the critical path: lifecycleScope.launch { ProfileStatusReporter.report(analytics::logProfileStatus) } compiled_non_matching is the status that pays for this whole function. It means a profile was compiled, but it does not match the DEX that shipped. That is exactly what a stale profile looks like in production.
For a quick local check without any code:
adb shell cmd package compile --reset app.tidewatch.android adb shell am broadcast -a androidx.profileinstaller.action.INSTALL_PROFILE \ app.tidewatch.android/androidx.profileinstaller.ProfileInstallReceiver adb shell cmd package compile -f -m speed-profile app.tidewatch.android adb shell am start -W -n app.tidewatch.android/.MainActivity The first command clears compiled state and any profile ART was holding. The broadcast asks profileinstaller to install the profile bundled in the APK again (without it, the reset leaves nothing for the next step to compile against). The third command compiles using that profile, and the last prints launch timing. Treat it as a smoke test only; section 3 covers real measurement.
Failure modes in generation
- The hollow profile. The journey times out, the test still passes, and the profile holds a few dozen startup rules. Fix it with the
error(...)in the helper above, and add a rule-count floor in CI (section 4). - Journeys that never stabilize.
collectrepeats the journey until the generated rules are identical across several consecutive runs (stableIterations, 3 by default), giving up aftermaxIterations(15 by default). If your journey hits a live backend, an A/B flag, or a time-dependent banner, the rules keep shifting and you either fail or record noise. Point generation at deterministic fixtures.strictStability = trueturns a wobbling profile into a hard failure instead of a quiet compromise. - Profiling everything. A profile that includes every screen grows the install-time compilation work and dilutes the hot path. Three to five journeys that match what users do in their first session is the right order of magnitude.
- Tags that exist only in your head. Rename
forecast_listin the UI and forget the test, and the journey now fails. That is the good outcome. The bad one is a generator that matches an old tag by accident and records the wrong screen.
3. Cold start measurement
Know what the clock covers
Macrobenchmark’s StartupTimingMetric reports two numbers. Time to initial display stops at the first frame. Time to full display stops at the first frame rendered once your code has reported itself fully drawn via reportFullyDrawn(). In Compose you get that by declaring ReportDrawnWhen (or a sibling such as ReportDrawn) as in the screen above. If you never report it, the second number does not exist.
Users do not care about your first frame. They care about when the list is usable. Track both, and gate on the full display number if your screen shows a skeleton first.
One benchmark, three modes
The honest way to measure a profile is to run the identical journey under different compilation modes and compare.
@RunWith(AndroidJUnit4::class) class StartupBenchmarks { @get:Rule val rule = MacrobenchmarkRule() @Test fun coldStartNoCompilation() = coldStart(CompilationMode.None()) @Test fun coldStartWithBaselineProfile() = coldStart( CompilationMode.Partial(baselineProfileMode = BaselineProfileMode.Require) ) @Test fun coldStartFullyCompiled() = coldStart(CompilationMode.Full()) private fun coldStart(mode: CompilationMode) = rule.measureRepeated( packageName = TARGET_PACKAGE, metrics = listOf(StartupTimingMetric()), compilationMode = mode, startupMode = StartupMode.COLD, iterations = 15, setupBlock = { pressHome() }, ) { startActivityAndWait() awaitForecast() // block must outlive reportFullyDrawn(), or TTFD goes missing } } BaselineProfileMode.Require is the detail that keeps this honest. If the profile is not installed on the device, the run throws instead of quietly measuring an unoptimized app and reporting a "profile win" of zero.
Run it on a physical, ideally mid-range device, because that is where startup pain lives:
./gradlew :baselineprofile:connectedBenchmarkAndroidTest Reading the result
The ordering to expect is usually simple: None is slowest, Partial with your profile is clearly faster, and Full is a ceiling you approach. On some memory-constrained devices Full can behave oddly because of its larger code footprint, so treat it as a reference point, not a guarantee. The gap between the first two is what the profile bought. The gap between the last two is headroom you have left.
The bars above are illustrative proportions, not measured data. Your absolute values depend on the device, the app, and the day. What carries over is the shape and the habit of comparing within one run, on one device, in one job.
Two experimental additions in the 1.5 line are worth trying once the basics are stable. ArtMetric can report JIT compilation and unoptimized class loading during a run, which tells you why a profile is not helping as much as expected. Startup Insights can point at common startup issues directly in the benchmark output, and the release notes describe it as experimental. Check the API reference for the annotations each one currently carries, and pin the version.
Failure modes in measurement
- Missing full-display numbers. The measured block returned before
reportFullyDrawn()fired. Wait for the same condition your app uses to declare itself drawn. - Emulator numbers in a gate. Emulators are fine for generating profiles and useless for judging a 5% regression. Library defaults refuse to run on them unless you suppress the error, and you should resist suppressing it for anything that blocks a merge.
- Warm device, cold story. A phone that just finished a long benchmark is thermally throttled. Let it rest, or you will “discover” regressions that are really heat.
- Averages. Startup distributions have a long tail. Compare medians for the headline and keep an eye on the maximum and on p90. A profile that helps the median but widens the tail is not the win it looks like.
- Measuring after a profile-less rebuild. If you rebuilt the app without regenerating,
Requirewill fail or you will measure a stale profile. That failure is working as intended.
4. CI automation
Two workflows with different jobs
Generation is slow, needs an emulator, and should run rarely. Verification is quick to trigger, needs real hardware, and should run on every change that could touch startup. Mixing them is how teams end up with a flaky pipeline nobody trusts.
Lane two first: regenerate on a schedule
# .github/workflows/refresh-baseline-profile.yml name: refresh-baseline-profile on: schedule: - cron: "0 3 * * 1" # Mondays, 03:00 UTC workflow_dispatch: jobs: generate: runs-on: ubuntu-latest timeout-minutes: 60 steps: - uses: actions/checkout@v4 - name: Enable KVM for the emulator run: | echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' \ | sudo tee /etc/udev/rules.d/99-kvm4all.rules sudo udevadm control --reload-rules sudo udevadm trigger --name-match=kvm - uses: actions/setup-java@v4 with: distribution: temurin java-version: 21 - uses: gradle/actions/setup-gradle@v4 - name: Generate profiles run: > ./gradlew :app:generateReleaseBaselineProfile -Pandroid.testoptions.manageddevices.emulator.gpu=swiftshader_indirect - name: Refuse suspiciously small profiles run: | file=app/src/release/generated/baselineProfiles/baseline-prof.txt rules=$(grep -c . "$file") echo "rules=$rules" # Set the floor to roughly 60% of your last known good profile. test "$rules" -ge 800 || { echo "Profile looks hollow"; exit 1; } - uses: peter-evans/create-pull-request@v7 with: branch: bot/refresh-baseline-profile title: "Refresh baseline and startup profiles" commit-message: "Refresh baseline and startup profiles" add-paths: app/src/release/generated/baselineProfiles/** The pull request is the safety net. A human sees the diff, and the verification lane runs on that PR like on any other.
Lane one: verify on every relevant change
# .github/workflows/startup-gate.yml name: startup-gate Source:https://dev.to/sivavishnu_r_1ee8971ed42d/teaching-art-what-matters-baseline-profiles-and-startup-profiles-step-by-step-4bea





