Perfetto, Battery Historian, and Macrobenchmark, used together, in an order that keeps you honest.
Every Android team has a story like this one. Someone merges a “battery optimization,” the release notes brag about it, and three weeks later the Play Console vitals look exactly the same. Nobody lied. Nobody measured, either.
Battery is the hardest performance metric to get right because the signal is small, the noise is large, and the phone is actively trying to fool you with thermal throttling, radio state, Doze, and whatever the user’s other apps decide to do. You cannot eyeball it, and you cannot trust a single run.
This post walks through a measurement workflow I’d defend in a design review. The running example is Fernwood, a fictional trail-journal app with three suspects: a breadcrumb uploader that pings the network on every GPS fix, a sync worker that holds a wake lock a little too generously, and a photo feed that serves JPEGs at full size. Every number in the charts is illustrative, so use the method, not the figures.
Three tools, three different questions
Before touching a device, be clear about which tool answers which question. Mixing them up is the most common way to produce a confident wrong answer.
- Macrobenchmark is your judge. It drives a scripted scenario repeatedly, collects metrics, and runs in CI. It tells you whether a change moved the needle.
- Perfetto is your detective. It records a system-wide trace (scheduler, CPU frequency, idle states, wake locks, power rails) and lets you query it with SQL. It tells you why.
- Battery Historian is your historian. It renders a bugreport as a long timeline of wake locks, jobs, alarms, and radio activity. It tells you what happened over hours, which is how you reproduce field complaints that a five-minute scenario never triggers.
The workflow below uses Macrobenchmark as the backbone and pulls in the other two when a number needs explaining.
1. Build a repeatable test setup
A measurement you cannot repeat is an anecdote. The rig has five jobs.
Pin the device and the environment
Use one physical device, one OS build, and one location. Emulators cannot give you meaningful power numbers, and Macrobenchmark will refuse to run on them unless you suppress the error, which is a way of lying to yourself with extra steps.
Freeze everything you can control:
# Fixed brightness, no adaptive brightness adb shell settings put system screen_brightness_mode 0 adb shell settings put system screen_brightness 100 # Same network every run: Wi-Fi on, cellular out of the picture adb shell cmd connectivity airplane-mode enable adb shell svc wifi enable # Fresh battery stats so the bugreport covers only this experiment adb shell dumpsys batterystats --reset Leave Doze and App Standby alone. They are part of the real environment, and disabling them makes your results flatter than production.
Make the app build identical across variants
Here is the trap that ruins A/B battery tests: building a separate APK per variant. Different builds mean different baseline profiles, different dex layouts, and different R8 decisions. Instead, ship one release-like build and flip behavior with flags that only exist for the benchmark:
enum class ImageCodec(val mime: String) { Jpeg("image/jpeg"), WebP("image/webp"), Avif("image/avif") } data class Variant( val batchedUploads: Boolean = false, val scopedWakeLock: Boolean = false, val codec: ImageCodec = ImageCodec.Jpeg, ) { companion object { const val EXTRA = "fernwood.variant" /** Only honored in the benchmark build type; production always gets the defaults. */ fun from(intent: Intent): Variant { if (!BuildConfig.EXPERIMENT_FLAGS_ENABLED) return Variant() return when (intent.getStringExtra(EXTRA)) { "batching" -> Variant(batchedUploads = true) "wakelock" -> Variant(scopedWakeLock = true) "webp" -> Variant(codec = ImageCodec.WebP) "avif" -> Variant(codec = ImageCodec.Avif) else -> Variant() } } } } The when has one branch per experiment and each branch flips exactly one field. That structure enforces step 3 of this post at the type level.
Set up the benchmark module
The benchmark lives in its own com.android.test module that targets a non-debuggable, profileable build:
// macrobenchmark/build.gradle.kts plugins { id("com.android.test") kotlin("android") } android { namespace = "com.fernwood.macrobenchmark" targetProjectPath = ":app" defaultConfig { minSdk = 31 } // This is the *test* module's build type. The :app benchmark build type it targets // must be non-debuggable and release-like (R8 on, profileable). buildTypes { create("benchmark") { isDebuggable = true; matchingFallbacks += "release" } } } dependencies { implementation("androidx.benchmark:benchmark-macro-junit4:<latest-stable>") implementation("androidx.test.uiautomator:uiautomator:<latest-stable>") } Check the current Macrobenchmark docs for the exact build-type wiring in your AGP version, since it has shifted over releases. The principle is stable: measure something that behaves like release.
Script the scenario so no human touches the phone
Humans scroll at different speeds. Scripts do not. This helper plays a fixed-duration feed session:
private fun MacrobenchmarkScope.scrollFeedFor(duration: Duration) { val feed = device.wait(Until.findObject(By.res(packageName, "feed")), 5_000) ?: error("Feed list not found. The scenario would silently measure an idle app.") feed.setGestureMargin(device.displayWidth / 5) val deadline = SystemClock.elapsedRealtime() + duration.inWholeMilliseconds while (SystemClock.elapsedRealtime() < deadline) { feed.fling(Direction.DOWN) device.waitForIdle() feed.fling(Direction.UP) device.waitForIdle() } } Note the error(...) on a missing view. A scenario that fails to find its target and carries on will happily report that your app uses very little battery, because it did nothing.
Collect power numbers
Power rails (on-device energy counters per subsystem) are the best signal available on supported hardware. The Macrobenchmark docs currently limit power metrics to physical Pixel 6 and newer devices, but support ultimately depends on the device’s power HAL, so verify per device rather than assuming. Macrobenchmark exposes rails as PowerMetric, which reports values such as energy<category>Uws (microwatt-seconds):
@RunWith(AndroidJUnit4::class) class FernwoodBatteryBenchmark { @get:Rule val rule = MacrobenchmarkRule() @Before fun requireRails() = assumeTrue("Device has no high-precision power rails", PowerMetric.deviceSupportsHighPrecisionTracking()) @Test fun baseline() = measure("baseline") @Test fun batching() = measure("batching") @Test fun wakelock() = measure("wakelock") @Test fun webp() = measure("webp") @OptIn(ExperimentalMetricApi::class) private fun measure(variant: String) = rule.measureRepeated( packageName = "com.fernwood.app", metrics = listOf( PowerMetric( PowerMetric.Type.Energy( mapOf( PowerCategory.CPU to PowerCategoryDisplayLevel.TOTAL, PowerCategory.NETWORK to PowerCategoryDisplayLevel.TOTAL, PowerCategory.DISPLAY to PowerCategoryDisplayLevel.TOTAL, ) ) ) ), iterations = 10, startupMode = StartupMode.COLD, compilationMode = CompilationMode.Partial(), setupBlock = { pressHome() }, ) { startActivityAndWait { it.putExtra(Variant.EXTRA, variant) } scrollFeedFor(3.minutes) } } PowerMetric is still experimental, so expect to adjust names when you upgrade. The assumeTrue guard matters: without it, an unsupported device produces a skipped or empty metric that looks like a clean run.
One hard truth to internalize now: rails measure the whole device subsystem, not your process. If a notification arrives or another app syncs mid-run, it lands in your numbers. That is why the rest of this workflow leans so heavily on repetition.
2. Measure the baseline first, and measure it badly on purpose
Resist the urge to change anything yet. Run baseline ten times and look at the spread.
The chart shows what a real baseline looks like: mostly clustered, with one run drifting high because the phone was still warm from the previous iteration. If you had run once and called it a day, you’d have had a one-in-ten chance of anchoring everything to that outlier.
Do three things with the baseline before moving on.
Compute the noise floor with an A/A test. Run baseline twice as two independent batches and compare them as if one were a variant. The "improvement" you see is pure noise, and it tells you the smallest real effect you can detect. If your A/A delta is ±3.5% and your optimization claims 2%, you have measured nothing.
Write down the median, not the mean. One thermal or background-sync outlier drags a mean around. A median shrugs it off.
Keep the raw traces. Add a Perfetto capture alongside Macrobenchmark for one baseline run so you have something to explain the numbers with later:
# trace_config.pbtxt duration_ms: 180000 buffers { size_kb: 65536 fill_policy: RING_BUFFER } data_sources { config { name: "android.power" android_power_config { battery_poll_ms: 1000 battery_counters: BATTERY_COUNTER_CHARGE battery_counters: BATTERY_COUNTER_CURRENT collect_power_rails: true } } } data_sources { config { name: "linux.ftrace" ftrace_config { ftrace_events: "power/cpu_frequency" ftrace_events: "power/cpu_idle" ftrace_events: "sched/sched_wakeup" atrace_categories: "power" atrace_apps: "com.fernwood.app" } } } adb shell perfetto -c - --txt -o /data/misc/perfetto-traces/baseline.pftrace < trace_config.pbtxt adb pull /data/misc/perfetto-traces/baseline.pftrace Open it in the Perfetto UI, or query it. This SQL gives you energy per rail across the capture, using the cumulative counters (track names can vary by device, so confirm them in the UI first):
SELECT t.name AS rail, MAX(c.value) - MIN(c.value) AS energy_uws FROM counter c JOIN counter_track t ON c.track_id = t.id WHERE t.name LIKE 'power.rails.%' GROUP BY t.name ORDER BY energy_uws DESC; For Fernwood, the baseline shows the modem rail is surprisingly loud for an app that mostly scrolls photos. That is the first clue, and it points at the uploader.
Failure modes at baseline
- Charging can contaminate results. A USB-connected phone can behave differently (charging-state changes, thermals), and
batterystatstreats it as plugged in. The Macrobenchmark docs don't require an unplugged device for power rails, but they do stress minimizing interference, so use wireless adb where you can.dumpsys battery unplugsimulates unplugging for stats purposes, but it does not make the hardware discharge like a real unplugged device, so treat it as a convenience, not ground truth. Remember to rundumpsys battery resetafterward. - Thermal state leaks between runs. Add a cool-down between iterations and check
adb shell dumpsys thermalservicebefore starting. Discard runs that began hot, but record that you did. - Run order bias. If all baseline runs happen before all variant runs, battery temperature and charge level drift systematically against one side. Rotate the order (baseline, variant, baseline, variant) when your harness allows it, or at minimum alternate days.
- Compilation state differs. A fresh install without a baseline profile runs more interpreted and JIT-compiled code early on, which adds CPU energy. How much depends on app size and workload, so measure it rather than assume it. Pin
CompilationModeand use it everywhere.
3. Change one variable at a time
This is the discipline that separates measurement from folklore. Each experiment changes one thing, runs on the same rig, and gets compared to the same frozen baseline.
If you stack all three optimizations into one build and see a 20% improvement, you have no idea which one earned it, and you won’t notice if one of them quietly made things worse while the others carried it.
Experiment A: batching network work
Fernwood’s uploader fires a request per GPS fix. Each transmission can keep the radio in a high-power state for a while afterward (the “tail”), so a trickle of tiny requests costs far more than the bytes suggest. Batching turns many small wakeups into a few larger ones.
The idiomatic Kotlin version drains a channel in size-or-time windows:
suspend fun <T> ReceiveChannel<T>.drainInBatches( maxSize: Int, maxWait: Duration, sink: suspend (List<T>) -> Unit, ) { while (true) { val first = receiveCatching().getOrNull() ?: return val batch = ArrayList<T>(maxSize).apply { add(first) } withTimeoutOrNull(maxWait) { while (batch.size < maxSize) { batch += receiveCatching().getOrNull() ?: break } } sink(batch) } } And it is used like this, with a bounded channel so a stalled network cannot grow memory without limit:
class BreadcrumbUploader( private val api: TrailApi, private val batched: Boolean, scope: CoroutineScope, // owned by a lifecycle: a service scope, not GlobalScope ) : Closeable { private val queue = Channel<Breadcrumb>( capacity = 512, onBufferOverflow = BufferOverflow.DROP_OLDEST, onUndeliveredElement = { Log.w(TAG, "Dropped breadcrumb: $it") }, ) private val worker: Job = scope.launch { if (batched) queue.drainInBatches(maxSize = 50, maxWait = 2.minutes) { api.upload(it) } else for (b in queue) api.upload(listOf(b)) } fun record(b: Breadcrumb) { queue.trySend(b) } /** Closing lets the worker flush what is already queued, then finish. */ override fun close() = queue.close() suspend fun awaitDrained() = worker.join() } Two lifecycle details are easy to miss. The worker is tied to the scope you pass in, so if that scope outlives the uploader, the coroutine lingers; call close() when tracking stops. And DROP_OLDEST means a long outage silently discards the oldest points, which is the right trade for a bounded buffer only if you log it (as above) and accept the loss.
What to look at in the trace: the modem power rail, and the count of distinct network bursts on the timeline. Fewer, fatter bursts is the signature of a working batcher.
Failure modes:
- The timeout can swallow an element. Cancelling a
receivewhile it is resuming can, in rare races, drop the element it just obtained, because of the prompt cancellation guarantee. I haven't reproduced this against every kotlinx.coroutines version, so check the behavior for the one you ship. If you cannot lose a data point, useonUndeliveredElement(as above) to re-queue or persist what falls out. - Batching delays freshness. A two-minute window is fine for breadcrumbs and wrong for chat. Measure the energy win and the latency cost, and report both.
- Your process dies with the batch in memory. The OS can kill you at any moment. Anything that must survive belongs in a durable queue (a Room table drained by WorkManager) rather than a coroutine’s local list.
- You batched in the app but a library still polls. Always confirm in the trace that the bursts really coalesced. A beautifully batched uploader can sit next to an analytics SDK that opens its own connection every thirty seconds.
Experiment B: wake locks
The sync worker holds a partial wake lock for the length of its work, and, worse, its release lives in a code path that an exception can skip:
// Before: the lock leaks if upload() throws, and it has no upper bound class SyncRunner(private val pm: PowerManager) { private val lock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "fernwood:sync") suspend fun run() { lock.acquire() upload() // throws? the CPU stays awake until the process dies lock.release() } } A scoped helper makes the correct thing the easy thing:
suspend fun <T> PowerManager.withPartialWakeLock( tag: String, timeout: Duration, block: suspend () -> T, ): T { val lock = newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "fernwood:$tag") .apply { setReferenceCounted(false) } lock.acquire(timeout.inWholeMilliseconds) // hard ceiling, even if we never reach finally try { return block() } finally { if (lock.isHeld) lock.release() } } // After suspend fun run() = pm.withPartialWakeLock("sync", timeout = 90.seconds) { upload() } setReferenceCounted(false) is deliberate. With reference counting on, a timed-out lock followed by a manual release() can throw an under-locked exception.
Ask the harder question too: does this code need a wake lock at all? WorkManager keeps the device awake while a worker is executing, so work scheduled through it usually needs no wake lock of its own. That guarantee covers only the worker’s execution window, though: work that must outlive it, or that has to run under OEM background restrictions, still calls for expedited work, a foreground service, or an explicit lock. For plain background sync, many “scoped wake lock” wins turn out to be “deleted wake lock” wins.
What to look at: the wake lock tracks in Perfetto (the power atrace category surfaces them, though slice naming varies by Android version, so inspect the track before writing a query) and, for long sessions, the wake lock rows in Battery Historian. Android vitals also flags apps with excessive cumulative partial wake lock time, so check the current threshold in the docs before deciding how much headroom you have.
Failure modes:
- The saving only shows up when the leak triggers. A scripted happy-path scenario never throws, so the “after” looks identical to the “before.” To measure the fix, inject failures (an offline server, a malformed response) in a dedicated scenario.
- Held time is not the same as energy. A lock held while the device was going to be awake anyway (screen on, foreground) costs little. A lock that keeps a sleeping device awake costs a lot. Check CPU idle residency, not just lock duration.
- Timeouts hide bugs. A 90-second ceiling stops the bleeding but also masks the reason the work takes that long. Log when the timeout fires.
Experiment C: image format
The feed serves full-size JPEGs. Switching to WebP (and AVIF on API 31+, where the platform decoder supports it) cuts bytes, which saves radio time. But decoding is CPU work, and a format that is smaller on the wire is not automatically cheaper to display.
Negotiating by Accept header keeps the client logic tiny:
class CodecNegotiationInterceptor(private val codec: () -> ImageCodec) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val wanted = codec().takeIf { it != ImageCodec.Avif || Build.VERSION.SDK_INT >= Build.VERSION_CODES.S } ?: ImageCodec.WebP val request = chain.request().newBuilder() .header("Accept", "${wanted.mime},image/*;q=0.5") .build() return chain.proceed(request) } } What to look at: the network rail and the CPU rail. A genuine win drops the first without inflating the second.
Failure modes:
- Encoded size is not the experiment. Compare at equal perceived quality, not equal quality parameters. A WebP at quality 80 and a JPEG at quality 80 are different pictures, and if the design team notices the blur, your optimization gets reverted.
- Decode cost can eat the savings. The more aggressive the codec, the more CPU per pixel on some hardware. This is exactly the sort of thing the CPU rail catches and a bytes-on-the-wire dashboard hides.
- The CDN cache is part of your test. A cold edge cache means different latency and sometimes different bytes. Warm it before you start, and do it the same way every run.
- Downsampling is the bigger lever. If the feed decodes a 4000-pixel photo into a 400-pixel card, requesting an appropriately sized rendition will likely beat any codec swap. Make that its own experiment, not a footnote. Source:https://dev.to/sivavishnu_r_1ee8971ed42d/proving-the-savings-a-field-guide-to-measuring-android-battery-drain-2em8




