Performance tooling
Tracing the keyboard with Perfetto, logging janky frames, Compose compiler reports, macrobenchmarks and the baseline profile.
A keyboard is judged a frame at a time: a stutter under a finger is felt long before it would show up in any average. This page covers the tools the project has for finding one, from the cheapest question (was a frame late?) to the most expensive (did this change make typing slower on a real phone?).
Everything here works on a release-like build. Release builds carry <profileable android:shell="true" />, so the shell’s profilers attach to whatever build is actually on the phone. Without it the shell refuses with “not debuggable, and not profileable by shell”, and the only way to see inside a frame would be a debug build: not the build anyone runs, and not timings worth trusting. It grants the shell user nothing else, so no debugger, no run-as and no access to app data. For iterating by hand, ./gradlew :app:installFullFast is release minus R8 and is close enough to judge typing latency.
Was a frame late?
Section titled “Was a frame late?”adb shell dumpsys gfxinfo com.wasimaster.wmkeyboard framestats prints the last 120 frames as CSV. Subtract IntendedVsync from FrameCompleted for a frame’s own cost, and compare consecutive IntendedVsync values: a gap much wider than one refresh interval is dropped frames, which is what a stutter actually is. Run reset before the interaction and read the stats straight after.
Logging janky frames as they happen
Section titled “Logging janky frames as they happen”The keyboard window and the settings app both carry a JankStats monitor that stays detached until you ask for it. It works on any build:
adb shell setprop log.tag.WMJank DEBUG # a summary each time the window goes awayadb shell setprop log.tag.WMJank VERBOSE # plus one line per janky frameadb logcat -s WMJankThe property is read each time the window comes back, so hide and show the keyboard (or leave and reopen the settings app) after setting it. A summary names the window, counts its frames and janky frames, and gives the worst one. Every janky frame is tagged with the screen that was showing: the keyboard’s open panel, or the settings route. A stutter that only happens in the emoji panel says so. A frame counts as janky by JankStats’ own measure, twice the display’s refresh interval. adb shell setprop log.tag.WMJank "" turns it off again.
Watching the keyboard adapt to load
Section titled “Watching the keyboard adapt to load”LoadGovernor (in core/settings) reads the keyboard’s own frame metrics, the strip’s measured pass cost, the thermal status and the trim-memory callbacks, and turns them into a LoadLevel that the service applies as budgets and, at HEAVY, as a settings view (underLoad). Each change of level can be logged:
adb shell setprop log.tag.WMLoad DEBUGadb logcat -s WMLoadA line names the new level, the phone’s class and the reading from each signal, plus the calm the next step down will wait for. To push a phone into the thermal path without heating it, adb shell cmd thermalservice override-status 3 reports a severe status (reset undoes it); adb shell am send-trim-memory com.wasimaster.wmkeyboard RUNNING_CRITICAL exercises the memory path. The user-facing description is When the phone is busy.
Work lanes and performance hints
Section titled “Work lanes and performance hints”The strip’s passes run on typingLane (one thread), glide decodes on glideLane (two), and warm-ups on idleLane (one, background priority). Each is a WorkLane (core/common/.../perf/WorkLane.kt): fixed threads at a set priority and, on Android 12 and later, an ADPF hint session (PerformanceHintManager) with a target of 30 ms per pass and 40 ms per decode. Each pass and decode reports its duration; TypingCadence marks the first key of a burst, which sends CPU_LOAD_UP on Android 13 and later. In a Perfetto trace the threads are named wmkb-suggest-1, wmkb-glide-1/-2 and wmkb-idle-1, so their core placement and clock can be read straight off the CPU tracks. Power saving turns the reports off.
The key preview bubbles come from a pool of four permanently composed bubbles (BubblePool), so a press recomposes a bubble that is already there rather than composing and disposing one. A fifth simultaneous bubble falls back to the old per-press composition.
Reading the field
Section titled “Reading the field”getTextBeforeCursor and the other reads on InputConnection block the thread that makes them until the app answers, and the app answers only after it has handled every edit sent before the read. After a letter typed into a search box, that includes filtering the list. A read made on the main thread right after an edit therefore holds the key’s animation, its haptics and the next touch for as long as the app takes, and no keyboard profile shows where the time went: the main thread is simply waiting.
- Nothing a letter needs for its own edit may read the field on the main thread. What is only for the strip or a chip reads it on another thread and follows the answer.
caretAtAddressis an example: it asks once for an ordinary word, because letters alone never turn one into an address (AddressToken.couldForm). - Work out the answer from what the keyboard already knows where that’s possible. A composing region that starts at 0 or right after the keyboard’s own space has no word in front of it.
- Every read goes through
FieldStallGuard. A read of 40 ms or more makes the fieldbusyfor five seconds. While it is, what follows a caret update (resuming the word at the caret, working out the shift) waits for the app on another thread first. A read of a second or more counts as a stall, and reads are skipped for up to three seconds, until the app reports a selection made after the stall. - The settings app’s own fields share the keyboard’s main thread, so any work a screen does per letter delays the next key. A screen that searches a list should search it off the main thread, once typing has paused. The word lists do this with
WordListSearch.
Where did a frame go?
Section titled “Where did a frame go?”scripts/perfetto.sh # 10 seconds; or scripts/perfetto.sh 20The script records a Perfetto system trace from the connected device while you type, pulls it into build/perfetto/, and prints the next step. Open the file at ui.perfetto.dev. The config it records with is config/perfetto/ime.pbtxt: scheduling and CPU frequency, the graphics, view and input trace categories, the frame timeline, and the app’s own trace sections. It needs Android 9 or later.
The keyboard marks its own work with named sections, all prefixed WM:, so it reads as more than one long Choreographer#doFrame:
| Section | What it covers |
|---|---|
WM:key | One key press, from the grid’s callback to the edit it makes |
WM:refreshSuggestions | The main-thread half of a strip refresh |
WM:suggest | The engine ranking words for what is being typed (background thread) |
WM:glideDecode | One glide stroke decoded to candidates (background thread) |
WM:updateSelection | The editor reporting that the caret moved |
WM:createInputView | Building the keyboard window’s Compose root |
WM:startInputView | A field gaining the keyboard |
They are defined in feature/ime/.../ime/ImeTrace.kt. A section costs one flag check when nothing is tracing, which is why they stay in release builds. To rank them, paste this into the trace’s Query (SQL) tab:
select name, count(*) as n, round(avg(dur) / 1e6, 2) as avg_ms, round(max(dur) / 1e6, 2) as max_msfrom slice where name like 'WM:%' group by name order by max_ms desc;Compose runs its measure and layout pass from AndroidComposeView.dispatchDraw. A screen that is slow to compose therefore shows up as one enormous Record View#draw(), not under measure or layout, which is the opposite of where you would look first.
Why does a composable recompose?
Section titled “Why does a composable recompose?”scripts/compose-reports.sh # feature/imescripts/compose-reports.sh feature/ime app # several modulesThe script recompiles the modules you name with the Compose compiler’s reports on. It then prints the compiler’s counts and lists every composable that takes an unstable parameter, naming those parameters. The raw reports land in each module’s build/compose/reports and build/compose/metrics. The switch behind the script works for any module that applies the Compose plugin:
./gradlew :feature:ime:compileFullDebugKotlin --rerun -PcomposeMetrics=true--rerun is not optional. The report destinations are not task inputs, so an up-to-date or cached compile writes nothing.
Read the parameter lists, not the skippable flag. Under strong skipping every restartable composable is reported skippable. What actually decides whether one skips is an unstable parameter, which is compared by instance, arriving as a new object on every recomposition. The keyboard service publishes a fresh KeyboardUiState for every keystroke. That is why the key composables take a resolved KeyVisual instead of the state, and the architecture tests fail if one of them starts taking it again.
Where did the memory go?
Section titled “Where did the memory go?”adb shell dumpsys meminfo com.wasimaster.wmkeyboard gives the totals by kind: the Java heap, the native heap (which holds bitmap pixels as well as the models), code, graphics. To see which objects hold the Java heap, take a heap dump with Perfetto. It works on the installed release build because of the profileable flag:
cat > /tmp/hprof.cfg <<'CFG'buffers { size_kb: 524288 fill_policy: DISCARD }data_sources { config { name: "android.java_hprof" java_hprof_config { pid: <pid> } } }duration_ms: 20000CFGadb push /tmp/hprof.cfg /data/local/tmp/hprof.cfgadb shell 'cat /data/local/tmp/hprof.cfg | perfetto --txt -c - -o /data/misc/perfetto-traces/wm.hprof.pftrace'adb pull /data/misc/perfetto-traces/wm.hprof.pftraceOpen it in the Perfetto UI’s heap graph, or query it with the perfetto Python package: include perfetto module android.memory.heap_graph.dominator_tree gives each object’s retained size (dominated_size_bytes, and dominated_native_size_bytes for bitmaps), so the biggest owners are one ORDER BY away. Bitmap pixels count as native, against the android.graphics.Bitmap that owns them.
The rest of the native heap needs heapprofd, which only sees allocations made while it is attached. Most of the keyboard’s native memory is allocated as it starts, so start a session that names the process before the process exists, then let it start (an install does it):
cat > /tmp/heapprofd.cfg <<'CFG'buffers { size_kb: 262144 fill_policy: DISCARD }data_sources { config { name: "android.heapprofd" heapprofd_config { sampling_interval_bytes: 16384 process_cmdline: "com.wasimaster.wmkeyboard" shmem_size_bytes: 16777216 continuous_dump_config { dump_phase_ms: 30000 dump_interval_ms: 60000 }} } }write_into_file: trueduration_ms: 2400000CFGadb push /tmp/heapprofd.cfg /data/local/tmp/heapprofd.cfgadb shell 'cat /data/local/tmp/heapprofd.cfg | perfetto --txt -c - -o /data/misc/perfetto-traces/native.pftrace --detach=wm'# ...the keyboard starts and is used for a minute or two...adb shell perfetto --attach=wm --stopEach dump in heap_profile_allocation holds what changed since the one before, so sum every dump of the process to get what it holds. Our libraries are loaded straight from the APK, so their frames map to base.apk with no names; walk up each callstack to the first Java frame to see which call into the engine made the allocation. On a CPH2481 in November 2026 the engine’s share at startup was about 21 MB: the learned words (UserLexicon.load), the punctuation and context models’ vocabularies, and the decoder’s rank tables. The rest was the GPU driver (libGLES_mali.so, 18 MB) and HWUI (12 MB).
What the keyboard gives back, and when:
- About 20 seconds after a panel closes, if the keyboard is back to plain typing: the media loader’s and the gallery’s thumbnail caches, and dynamic stickers’ parsed documents and art library (
schedulePanelTriminWMKeyboardService). A picture still on screen keeps its own bitmap; emptying a Coil cache only drops the cache’s reference. - Half a minute after the last settings screen stops: what only those screens use, such as the settings search index, the language and path-strip indexes, the settings history, the vocabulary packs the packs screen read and the icon packs’ parsed lists (
StartedActivities.onAllStopped). The keyboard runs in the same process and outlives the settings app by days, so these used to stay with it. The next screen that needs one builds it again. - Two minutes after the keyboard hides, and on trim-memory:
releaseHeavyEngines, which unloads the models, decoded app icons and icon packs, thumbnails, dynamic stickers, the search boxes’ stem cache and vectors by meaning, the emoji search index, background photos, theme card pictures and the layouts the settings app’s cards parsed. Among the models are IndicXlit (13 MB of ONNX a direction) and PaddleOCR (11 MB), which nothing let go of before. - Two minutes after the last reading aloud, whoever asked for it: the open MMS or Kokoro voice (
SpeechOut), 114 MB of ONNX model each. Five minutes after the last on-device translation from any caller, the AI’s tool and the selection menu’s WM Translate included: every translation engine’s models (OfflineTranslation). Neither waits for the keyboard to hide, since the settings app’s screens use them in the same process.
Caches are bounded by bytes, not by entries, wherever the entries vary in size. Dynamic stickers’ documents are an example: a compiled built-in scene is some 400 KB of JSON tree and an imported Lottie file can be fifty times that, so DynStickerStore weighs each one and keeps 4 MB of them. The art library is the other half of that store: 2.4 MB of JSON that parsed whole came to 28 MB of heap, so ArtLibrary keeps the bytes and parses one drawing when a scene asks for it. Coil’s two loaders keep a twentieth of the app’s heap class each. In the engine, the .wmlm and .wmpt readers look words up in the mapped file (vocab.rs) instead of copying the vocabulary into hash maps, which took 3.4 MB and 5.1 MB of native heap, and the learned words keep one small record a word, with each word’s followers packed in ranking order into one byte array and the trie’s nodes in one array of fixed-size records. A store at its caps (9,000 words, 141,626 followers) holds 2.9 MB that way, where eight maps keyed by their own strings and a vector a word held 9.3 MB, and loading its 2 MB file peaks at 13 MB instead of 37 MB because the file is read in place rather than through a JSON tree. The decoder’s rank tables keep each distinct frequency once, with a count of the words at or below it: 35 KB for the English lists where a frequency a word took 1.2 MB. While the keyboard is hidden the idle release also gives back the decoders’ working memory (NativeEngine.trimIdle): the glide workspace a long stroke grew, about 5.7 MB on each thread that glided, and the tap decoder’s search of the last word, about 1.3 MB after a long one. The next stroke or word builds them again and reads exactly the same; a decoder in use at that moment lets go when its call ends. A glass theme’s blurred backdrop is kept at the quarter size the blur ran at, 0.8 MB where a full-size copy of a 12-megapixel photo was 12 MB, and on Android 12 and later board photos and key textures are decoded straight into graphics memory, so they are not held once in the heap and again as a texture.
Tables the keyboard keeps all day are packed: one string of entries end to end with an array of offsets, searched by halving, instead of a hash map of boxed objects. The emoji keywords the strip looks up on every word take 183 KB that way where a map of lists took 1.3 MB, for English and Bengali. The Unicode character names take 1.1 MB where their search table took 15 MB. The offensive-word list is 96 KB for English’s 7,748 words, which two hash sets made about 840 KB, and the phonetic spelling maps shrink the same way. The emoji search index is built by the first search rather than at startup, and goes with the idle release. A compiled word list held in Kotlin (PackedTrie) takes 11 bytes a node instead of 19, and the glide shape store’s published snapshot shares the stored shapes rather than copying each one.
Compiled regular expressions are a quieter cost. Android’s regex engine is ICU’s, and a pattern with a Unicode class such as \p{L} holds 20 to 100 KB of native sets for the rest of the process once it is compiled. Patterns kept in objects are by lazy, so a class touched for one cheap function no longer compiles thirty of them, and the strip’s smart suggestions reach a pattern only once the text could match it: an amount, a unit or a sum needs a digit, a lookup its own lead words. Keyboard start and plain English typing compile about 150 KB of patterns that way, where they compiled about 1.2 MB.
Macrobenchmarks and the baseline profile
Section titled “Macrobenchmarks and the baseline profile”The :benchmark module holds a baseline profile generator and three macrobenchmarks, run on a real device against a release-like build. It joins the build only with -Pwmkb.benchmark=true, for two reasons. Applying the baseline profile plugin adds two build types to every flavour pair of :app, which every other build would then pay for. And its tests install a build over the app on the connected device.
The benchmarks bring the keyboard up over the settings app’s own search field, then tap and glide at fixed fractions of the keyboard’s window. The keys carry no accessibility labels unless a screen reader is on, so they can’t be found by name. A fresh install is skipped past onboarding first.
The baseline profile
Section titled “The baseline profile”A baseline profile lists the methods ART compiles ahead of time at install instead of interpreting them until the JIT gets round to them. For a keyboard this matters more than for most apps. The IME process is killed and restarted all day whenever memory is short, and a low-end phone pays the warm-up cost on every one of those starts.
The app has two profiles, and every build packages both:
app/src/main/baseline-prof.txtis written by hand: wildcard rules over the keyboard’s runtime and the settings app. It says why each part is in, and why the tool subsystems are left out.app/src/intlRelease/baselineProfiles/is generated from a recorded journey: open the settings app, bring the keyboard up over search, type, glide, type again. It is added to every variant, not only the one it was recorded from.
To regenerate the second one, with a device on API 33 or later connected (or a rooted one on API 28 or later):
./gradlew :app:generateIntlReleaseBaselineProfile -Pwmkb.benchmark=trueCommit what it writes. It is filtered to the app’s own classes, since the libraries ship profiles of their own. Use this variant’s task rather than the plugin’s merged generateBaselineProfile: the merged task would run the journey once for each of eight variants to produce the same file.
Benchmarks
Section titled “Benchmarks”./gradlew :benchmark:connectedIntlBenchmarkReleaseAndroidTest -Pwmkb.benchmark=true \ -Pandroid.testInstrumentationRunnerArguments.class=com.wasimaster.wmkeyboard.benchmark.KeyboardBenchmarkStartupBenchmarkcold-starts the settings app twice over, with and without the profile. The gap between the two is what the profile is worth. If it closes, the profile has stopped covering what start-up runs.KeyboardBenchmark.coldShowbrings the keyboard up in a process that was not running, and reportsWM:createInputView,WM:startInputViewand frame timings.KeyboardBenchmark.typingand.glidingreport frame timings plus the summed time inWM:key,WM:refreshSuggestions,WM:suggestandWM:glideDecode. A regression then shows up as the section that grew, not only as more jank.
Results are printed in the test output and written as JSON under benchmark/build/outputs/connected_android_test_additional_output/. Each iteration’s trace is saved beside them and opens in Perfetto.
