DEV Community

Cover image for Proving the Savings: A Field Guide to Measuring Android Battery Drain
Android Expert
Android Expert

Posted on Originally published at Medium

Proving the Savings: A Field Guide to Measuring Android Battery Drain

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.

tool-comparison

  • 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.

test-rig

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
Enter fullscreen mode Exit fullscreen mode

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()
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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>")
}
Enter fullscreen mode Exit fullscreen mode

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()
    }
}
Enter fullscreen mode Exit fullscreen mode

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)
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

baseline-variance

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"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
adb shell perfetto -c - --txt -o /data/misc/perfetto-traces/baseline.pftrace < trace_config.pbtxt
adb pull /data/misc/perfetto-traces/baseline.pftrace
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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 batterystats treats 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 unplug simulates 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 run dumpsys battery reset afterward.
  • Thermal state leaks between runs. Add a cool-down between iterations and check adb shell dumpsys thermalservice before 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 CompilationMode and 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.

one-variable

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)
    }
}
Enter fullscreen mode Exit fullscreen mode

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()
}
Enter fullscreen mode Exit fullscreen mode

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 receive while 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, use onUndeliveredElement (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()
    }
}
Enter fullscreen mode Exit fullscreen mode

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() }
Enter fullscreen mode Exit fullscreen mode

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)
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

4. Compare and report

Ten numbers per variant do not speak for themselves. The report has to say how big the change is, how sure you are, and whether it clears the noise.

Use a median and a confidence interval, not a bare average

A small bootstrap gives you an honest interval without assuming a distribution:

data class Delta(val medianPct: Double, val lowPct: Double, val highPct: Double) {
    /** A real effect must exclude zero AND exceed the A/A noise floor. */
    fun isReal(noiseFloorPct: Double) =
        (lowPct > 0 || highPct < 0) && abs(medianPct) > noiseFloorPct
}

fun bootstrapDelta(
    baseline: List<Double>,
    variant: List<Double>,
    resamples: Int = 10_000,
    random: Random = Random(42),
): Delta {
    fun median(xs: List<Double>): Double {
        val s = xs.sorted()
        return (s[(s.size - 1) / 2] + s[s.size / 2]) / 2
    }
    fun pct(b: List<Double>, v: List<Double>) = (median(v) - median(b)) / median(b) * 100

    val samples = DoubleArray(resamples) {
        pct(
            List(baseline.size) { baseline.random(random) },
            List(variant.size) { variant.random(random) },
        )
    }.sortedArray()

    return Delta(
        medianPct = pct(baseline, variant),
        lowPct = samples[(resamples * 0.025).toInt()],
        highPct = samples[(resamples * 0.975).toInt()],
    )
}
Enter fullscreen mode Exit fullscreen mode

Feed it the per-iteration energy values from the *-benchmarkData.json file Macrobenchmark writes. The fixed seed makes the report reproducible, so two people reading the same data get the same interval.

Show the result with its uncertainty

results

Read this chart the way a reviewer should. Batching and the scoped wake lock clear the noise band with room to spare. The WebP change does not: its interval overlaps the noise, so the honest conclusion is “not demonstrated,” not “saves 2%.” And the combined build, which was measured after the individual experiments, lands close to the sum of its parts, which is a useful sanity check that the effects were independent.

What belongs in the write-up

  • The device model, OS build, and app commit SHA, so someone can reproduce it.
  • Median and interval per variant, plus the A/A noise floor.
  • The mechanism, backed by a Perfetto screenshot or query: “the modem rail dropped because 412 upload bursts became 9,” not just “it dropped.”
  • The cost side: added latency, added complexity, added memory.
  • What you did not measure. A five-minute foreground scenario says nothing about overnight idle drain, which is where wake lock leaks live. For that, capture a bugreport after a long soak and open it in Battery Historian.

Wire it into CI, with humility

Run the benchmark on a pinned device in a lab or a device farm, store results per commit, and alert on trends rather than single runs. Gate on the interval, not the point estimate, or you will spend your life chasing flaky failures.

A pre-flight checklist for the skeptics

Before you publish a battery claim, make sure you can answer yes to each of these:

  • Did I run on a real, unplugged-or-controlled device, with temperature in check?
  • Did every variant come from the same build, toggled by a flag?
  • Did I run an A/A test and know my noise floor?
  • Did I change exactly one thing per experiment?
  • Did I use enough iterations, and report a median and an interval?
  • Can I point at a trace that shows why the number moved?
  • Did I check the cost side (latency, CPU, memory, correctness)?
  • Did I note what the scenario cannot see?

🔚 Closing thought

The tools are the easy part. Perfetto, Historian, and Macrobenchmark are all well-documented and free. What is rare is the discipline: freezing the environment, measuring the baseline before being tempted to fix it, changing one thing, and reporting uncertainty as a feature rather than an embarrassment.

Do that, and the next time someone ships a “battery optimization,” your team will be the one that can say, with a trace and an interval to back it up, whether it worked.

🔐 Master Android Architecture: Volume 1, Foundations and Core Architecture

Most Android architecture advice is a diagram and a list of rules. This book teaches the judgment behind them. You build NowReading from an empty project into an offline-first app, one decision at a time. It covers the principles behind Google’s layered architecture, then every layer in depth: Compose and state holders, MVI, navigation, the domain layer, Room and DataStore, networking, offline-first sync, Hilt, coroutines and Flow, background work and error handling. Every chapter opens with a realistic failure and ends with pitfalls, trade-offs, review questions and an exercise.

Top comments (0)