A news feed janks on scroll; how would you write a Jetpack Macrobenchmark with FrameTimingMetric and TraceSectionMetric to prove a fix, and how do you read its results?
answer
- WARM start, setupBlock opens the feed
- the tail, not the median
- positive overrun means a dropped frame
- trace section around the row
- Sum reports count and total
basics
~20 sScroll the feed in a Macrobenchmark's measureBlock with FrameTimingMetric and a TraceSectionMetric around the row code. Compare P90 to P99 frameOverrunMs, where positive values are dropped frames, plus the section's count and total, before and after.
solid answer
~40 sI'd write a Macrobenchmark with `startupMode = StartupMode.WARM`, a `setupBlock` that opens the feed, and a `measureBlock` that flings the list through UI Automator, keeping one fixed `compilationMode` and about ten iterations. `FrameTimingMetric` reports `frameOverrunMs` (API 31+, positive means a missed deadline), `frameDurationCpuMs` on the UI thread and RenderThread, and `frameCount`, at P50 to P99; jank shows in the tail. I'd wrap the row in `trace("FeedRow") { }` in the app and add `TraceSectionMetric("FeedRow", Mode.Sum)`, an `@ExperimentalMetricApi`, to see how often and how long it runs. The target must be a non-debuggable, profileable build, or the library stops with a `DEBUGGABLE` error.
code
kotlin · 26 lines@OptIn(ExperimentalMetricApi::class)
@Test
fun scrollFeed() = benchmarkRule.measureRepeated(
packageName = "com.example.feed",
metrics = listOf(
FrameTimingMetric(),
TraceSectionMetric("FeedRow", TraceSectionMetric.Mode.Sum),
),
compilationMode = CompilationMode.Partial(BaselineProfileMode.Require),
startupMode = StartupMode.WARM,
iterations = 10,
setupBlock = {
pressHome()
startActivityAndWait()
},
) {
val feed = device.findObject(By.res("feed"))
feed.setGestureMargin(device.displayWidth / 5)
feed.fling(Direction.DOWN)
}
// In the app module
@Composable
fun FeedRow(item: FeedItem) = trace("FeedRow") {
ArticleCard(item)
}go deeper
Recall that FrameTimingMetric reports per-frame timings as percentiles and that the scroll happens through UI Automator in measureBlock.
Explain frameOverrunMs versus frameDurationCpuMs, why the tail percentiles matter, and what frameCount is for.
Show the full proof: fixed compilation and startup modes, a non-debuggable profileable target, a trace section around the changed code, and reading the worst iteration's trace.
Decide which journeys get frame benchmarks, which percentile the team treats as its jank signal, and who owns instrumenting trace sections in app code.
## The scenario Users report that a news feed stutters while scrolling. A teammate changes how each row is built and says it is smoother. To prove it, you need a scroll benchmark whose numbers move when jank moves, and a way to see whether the row itself got cheaper. ## Writing the benchmark A frame benchmark is a **Macrobenchmark** in the `com.android.test` module. The parts that matter: - **`metrics`**: `FrameTimingMetric()` for frame timing, plus a `TraceSectionMetric` for the work you changed. - **`startupMode = StartupMode.WARM`** and a `setupBlock` that opens the feed, so each iteration starts on the same screen without timing the launch. - **`measureBlock`**: the scroll itself, done through UI Automator; for example find the list by its resource id (in Compose, enable `testTagAsResourceId` so test tags become resource ids) and `fling(Direction.DOWN)`. - **`compilationMode`**: pick one, such as `Partial(BaselineProfileMode.Require)`, and keep it identical for the before and after runs. - **`iterations`**: enough runs, for example 10, that the percentiles settle. `TraceSectionMetric` is marked `@ExperimentalMetricApi`, so the test opts in with `@OptIn(ExperimentalMetricApi::class)`. ## FrameTimingMetric: what each value means `FrameTimingMetric` reads every frame produced during `measureBlock` and reports a distribution at **P50, P90, P95 and P99**: 1. **`frameOverrunMs`** (API 31+) is how much a frame missed its deadline by. **Positive values are dropped frames**, visible stutter; negative values say how much time was left over. Prefer it for detecting regressions because it accounts for higher and variable refresh rates. 2. **`frameDurationCpuMs`** is how long the frame took on the CPU, on both the UI thread and the RenderThread. It does not include time before the frame started. 3. **`frameCount`** is the number of frames produced. It explains odd results: removing needless trivial frames can make the other two values *look* worse even though the app got better. Jank lives in the tail. A P50 that barely moves with a P99 `frameOverrunMs` going from positive to negative is a real fix; a better P50 with the same positive P99 is not. ## TraceSectionMetric: measuring your own code `FrameTimingMetric` says frames were slow; `TraceSectionMetric` says whether *your* code is why. Wrap the work in the app with a trace section, `trace("FeedRow") { ... }` from AndroidX Tracing or `Trace.beginSection` / `Trace.endSection`, then measure it by name: - `TraceSectionMetric("FeedRow", TraceSectionMetric.Mode.Sum)` reports how many times the section ran (`FeedRowCount`) and its total duration (`FeedRowSumMs`) per iteration, summarized as min, median and max. A count that jumps tells you the row is being rebuilt more often than it should. - **Modes**: `Sum` (the default), `First`, `Min`, `Max`, `Count` and `Average`. With `Sum`, `Count` and `Average`, a section that never appears reports **0**; with `First`, `Min` and `Max` it reports nothing. - `%` works as a wildcard, as in `"%FeedRow%"`, which helps with sections whose names carry extra text. - `targetPackageOnly` defaults to `true`: only sections from the target app's process count. In a Compose app, composition tracing (the `runtime-tracing` dependency plus extra setup in the benchmark module) can surface composables as sections without manual wrappers; without that setup a wildcard on a composable's name finds nothing. ## Making the numbers trustworthy - **Non-debuggable target.** If the app is built with `debuggable=true`, Macrobenchmark stops with a `DEBUGGABLE` error: debuggable code runs far slower, and an improvement there may not carry over to release, or may even regress it. Benchmark a `benchmark` build type copied from release and signed with a debug key, and make it `<profileable>`. - **Same device model, real hardware.** Emulators share the host's resources. - **Compare like with like**: same compilation mode, startup mode, iteration count and data set. - **Read the traces.** Each iteration writes a trace file next to the JSON results; open the worst one to see which work overran. | Value | Source | Read it as | |---|---|---| | `frameOverrunMs` P90 to P99 | `FrameTimingMetric` | positive means visible jank | | `frameDurationCpuMs` | `FrameTimingMetric` | CPU cost per frame | | `frameCount` | `FrameTimingMetric` | sanity check on the others | | `FeedRowCount` / `FeedRowSumMs` | `TraceSectionMetric` | how often and how long your row runs | Frame budgets as a product decision, and reading a trace by hand in the IDE, are separate topics; this benchmark is what turns "it feels smoother" into a number.
- After the fix, frameDurationCpuMs and frameOverrunMs got slightly worse but users say scrolling is smoother; how can that be?Check `frameCount`. If the fix stopped the app from producing needless trivial frames, the remaining frames are on average heavier, so per-frame CPU time and overrun percentiles can rise even though less work is done overall. The metric documentation names `frameCount` as the value that explains such shifts.
- Why might TraceSectionMetric("%FeedRow%") report 0 even though the composable ran during the scroll?With `Mode.Sum` a section that never appears in the trace reports 0. A composable only shows as a section if the app wraps it in `trace()` or composition tracing is fully set up for the benchmark; adding the runtime-tracing dependency alone is not enough for Macrobenchmark capture. Also `targetPackageOnly` defaults to true, so sections outside the app's process are ignored.
- A better P50 frame time proves the jank is fixed.
- Negative frameOverrunMs values mean frames were dropped.
- Benchmarking the debuggable build is fine for comparing before and after.
- Compare a Full-compiled before run with a Partial-compiled after run.
- TraceSectionMetric finds composables by name with no app-side tracing.