|
| 1 | +# Runtime performance tooling |
| 2 | + |
| 3 | +Scripts for A/B benchmarks of the Android runtime on a real device: build one benchmark |
| 4 | +APK, run labelled rounds under a device lock, and turn the logs into a ratio table. |
| 5 | +They use bash and python3 only. Run them with `bash`, even from zsh. |
| 6 | + |
| 7 | +```bash |
| 8 | +OUT=/tmp/ns-perf/my-experiment |
| 9 | +# 1. one release APK that carries every label (variants 0, 1, 2 below) |
| 10 | +bash tools/perf/build.sh --out "$OUT/apks" --label exp --variants --ccache |
| 11 | +# 2. rounds on one device: base and its A/A copy base2 both run variant 0 |
| 12 | +bash tools/perf/run.sh --serial <adb-serial> --out "$OUT/runs" --apk "$OUT/apks/exp.apk" \ |
| 13 | + --labels "base=0 base2=0 cache=1 nocache=2" --rounds 6 \ |
| 14 | + --filter 'static.noop()|field.get int|callback.noArgs()' |
| 15 | +# 3. the table |
| 16 | +python3 tools/perf/table.py "$OUT/runs" --anchor base --aa base2 |
| 17 | +``` |
| 18 | + |
| 19 | +## The protocol, and why |
| 20 | + |
| 21 | +Each rule below cost a wrong result at least once. |
| 22 | + |
| 23 | +- **Release, optimized APK only.** The debug runtime is built `-O0` and debuggable apps |
| 24 | + run with CheckJNI. `build.sh` builds `:app:assembleRelease -Poptimized` signed with the |
| 25 | + debug keystore, because shipped apps use the optimized runtime. |
| 26 | +- **Install, then `cmd package compile -m speed -f`, then throw away the first launch.** |
| 27 | + On some phones the first launch after an install runs about 1.6x slower from about |
| 28 | + 3.5 s into the process, on every row. `run.sh` installs once per round (once per APK in a |
| 29 | + round, if labels use separate APKs), speed-compiles, runs one discarded launch |
| 30 | + (`--discard-secs`, default 8 s), and measures only relaunches. |
| 31 | +- **Every label runs in every round, in rotated order.** Ratios are taken within a round |
| 32 | + (`table.py`), because absolute times swing between launches by core and frequency |
| 33 | + state. Rotation keeps a label from always running first or last. |
| 34 | +- **An A/A label.** It is a second label with the anchor's exact configuration. Its |
| 35 | + ratio range is the noise floor, and `table.py --aa` compares every other range against it. |
| 36 | +- **One device per experiment.** `run.sh` records the serial in `<out>/device.txt` and |
| 37 | + refuses to add rounds from another device to the same directory. |
| 38 | +- **No builds while measuring.** A concurrent gradle build once inflated every row by |
| 39 | + 50% (on an emulator, which shares the host's CPU). `launches.tsv` records the host's |
| 40 | + load average and the device's thermal status for every launch, so you can check. |
| 41 | + |
| 42 | +## Run-time variants (`--variants`) |
| 43 | + |
| 44 | +Building one APK per label is slow. It also leaves several APKs that each need an |
| 45 | +install, a speed compile and a discarded launch every round. Instead, a benchmark build |
| 46 | +can carry every label as a run-time branch: |
| 47 | + |
| 48 | +- `build.sh --variants` passes `-PbenchVariants`, which sets the CMake option |
| 49 | + `NS_BENCH_VARIANTS` (off by default). The runtime then reads the system property |
| 50 | + `debug.ns.benchvariant` (an integer, default 0) once, when `libNativeScript.so` loads. |
| 51 | +- C++: `#include "BenchVariant.h"`, then `if (tns::BenchVariant() == 1) { ... }`. |
| 52 | + The accessor is an inline read of a process global. Without the option it is |
| 53 | + `constexpr 0`, so the branches compile away and nothing reads the property. |
| 54 | +- JS: `globalThis.__benchVariant`, a read-only number. It is `undefined` without the |
| 55 | + option, so use `(globalThis.__benchVariant | 0)`. |
| 56 | +- Java can read the property itself (`getprop debug.ns.benchvariant`); the test app's |
| 57 | + `JniBench.getProp` shows how. |
| 58 | +- `run.sh` sets the property before each launch. The runtime logs |
| 59 | + `NS_BENCH_VARIANT=<n>` at startup, and `run.sh` checks it against the label. A |
| 60 | + mismatch marks the launch `wrong-variant` and keeps its log as `*.log.bad`. A missing |
| 61 | + line aborts the run, because the APK was built without `--variants`. |
| 62 | + |
| 63 | +**Convention.** Variant branches live in local, bench-only commits on top of the change |
| 64 | +under test, and are never pushed. Variant 0 is the code as it would ship. Each other |
| 65 | +number is one alternative, and the A/A label also uses 0. |
| 66 | + |
| 67 | +**Caveat: one binary, one code layout.** Every variant shares the same compiled code. |
| 68 | +An alternative whose effect depends on code layout, inlining or I-cache footprint |
| 69 | +(adding a large function, moving a hot loop) can measure differently once it is the |
| 70 | +only code path. The A/A pair catches noise, not layout. Confirm a layout-sensitive |
| 71 | +result, or any result you will publish, with separate APKs: one `build.sh` per side, run |
| 72 | +as `base=base.apk base2=base.apk new=new.apk`. Build both sides with the same `--ccache` |
| 73 | +setting. A ccache build rewrites source paths (`__FILE__`), so it is not byte-identical |
| 74 | +to a build without ccache. |
| 75 | + |
| 76 | +## ccache (`--ccache`) |
| 77 | + |
| 78 | +`--ccache` builds through ccache with settings that share cache entries across |
| 79 | +checkouts. The runtime's existing switch accepts `-PuseCCache` (used by CI and |
| 80 | +packaging), `-PuseCcache`, or `NS_USE_CCACHE=1` in the environment. `build.sh` also sets: |
| 81 | + |
| 82 | +| variable | value | why | |
| 83 | +|---|---|---| |
| 84 | +| `CCACHE_DIR` | `$NS_PERF_CCACHE_DIR`, else `~/Library/Caches/ns-android-ccache` | a dedicated cache, so unrelated projects don't evict runtime objects | |
| 85 | +| `CCACHE_MAXSIZE` | `$NS_PERF_CCACHE_MAXSIZE`, else `3G` | one arm64 configuration takes about 25 MB, so 3 GB holds many | |
| 86 | +| `CCACHE_BASEDIR` | the checkout root | CMake passes absolute source and `-I` paths. ccache rewrites them relative to the build directory, which is the same in every checkout | |
| 87 | +| `CCACHE_NOHASHDIR` | `1` | `-g` makes ccache hash the working directory by default, which differs per checkout | |
| 88 | + |
| 89 | +Measured on an M-series Mac with a host load average of about 8 (arm64, |
| 90 | +`-Poptimized --variants`, whole `build.sh` wall time): |
| 91 | + |
| 92 | +| build | wall time | ccache | |
| 93 | +|---|---:|---| |
| 94 | +| first build in a fresh worktree, empty cache | 28 s | 79 misses | |
| 95 | +| first build in a second worktree (different path), same sources | 18 s | 79/79 hits | |
| 96 | +| same worktree, native build state deleted, no ccache | 22 s | — | |
| 97 | +| same worktree, native build state deleted, warm cache | 12 s | 79/79 hits | |
| 98 | + |
| 99 | +The rest of a build (gradle, Java, dex, packaging) is not cached, and a build that only |
| 100 | +changes JS or Java reuses the native objects anyway. ccache pays off in fresh worktrees, |
| 101 | +after switching a CMake flag (`-Poptimized`, `--variants`), each of which recompiles |
| 102 | +everything, and on a busy host, where native compilation slows the most. |
| 103 | +`ccache -s` with the same `CCACHE_DIR` shows totals. |
| 104 | + |
| 105 | +## Device lock and device selection |
| 106 | + |
| 107 | +Several sessions share each device, so every command that touches one holds a lock |
| 108 | +for its whole session. `run.sh` takes it per round, so other sessions can interleave |
| 109 | +between rounds. |
| 110 | + |
| 111 | +- **The lock** is a directory created with `mkdir`. It is |
| 112 | + `$NS_PERF_LOCK`, or `--lock PATH`, or else |
| 113 | + `${NS_PERF_LOCK_DIR:-~/.cache/ns-perf/locks}/phone-<serial>.lock`. To share an |
| 114 | + existing lock with other tools, point `NS_PERF_LOCK` (or `--lock`) at the same path. |
| 115 | + The holder writes an `owner` file inside the lock, and waiters print it. |
| 116 | +- **Cleanup happens only while the lock is held.** That covers force-stopping the app |
| 117 | + and clearing the `debug.ns.*` properties. A process that is still waiting, or that is |
| 118 | + interrupted while waiting, touches nothing. A stale lock is never broken |
| 119 | + automatically: check `owner` and remove it by hand. |
| 120 | +- **`--serial` is required.** The scripts never pick a device for you. Serials in |
| 121 | + `NS_PERF_PROTECTED_SERIALS` (default `emulator-5554`) are refused outright. |
| 122 | + |
| 123 | +## Commands |
| 124 | + |
| 125 | +### `build.sh` |
| 126 | + |
| 127 | +``` |
| 128 | +build.sh --out DIR [--label NAME] [--variants] [--ccache] [--profileable] [--regular] |
| 129 | + [--abi ABI] [--repo DIR] [--keep-build] |
| 130 | +``` |
| 131 | + |
| 132 | +This builds `DIR/<label>.apk`, plus the unstripped `DIR/<label>.syms/libNativeScript.so` for |
| 133 | +simpleperf symbols. It writes `DIR/<label>.build.txt` with the commit, whether the tree |
| 134 | +was dirty, the flags, the `.so` hash, the wall time and the ccache hits. It runs gradle |
| 135 | +under `nice -n 19`. It deletes `app/build` and `assets/metadata` first (stale metadata |
| 136 | +hides new Java classes from JS), and deletes `app/build` again afterwards to save disk. |
| 137 | +`--profileable` adds `<profileable android:shell="true"/>` to the test app manifest for |
| 138 | +this one build and restores the file afterwards. |
| 139 | + |
| 140 | +### `run.sh` |
| 141 | + |
| 142 | +``` |
| 143 | +run.sh --serial S --out DIR --labels "NAME=SPEC ..." [--apk FILE] [--rounds N] |
| 144 | + [--first-round K] [--bench NAME] [--filter F | --groups FILE] [--scale N] |
| 145 | + [--lock PATH] [--no-wait] [--gap SECS] [--discard-secs N] [--no-discard] [--timeout SECS] |
| 146 | +``` |
| 147 | + |
| 148 | +- A label spec is `VARIANT` (a variant of `--apk`), `APK` or `APK:VARIANT`. |
| 149 | +- `--groups FILE` runs one launch per line and label; each line is a filter. Use it to keep |
| 150 | + rows that disturb each other (GC-heavy rows, large heaps) out of the same process. |
| 151 | +- `--first-round K` appends more rounds to an existing directory. |
| 152 | +- Output: |
| 153 | + - `DIR/<label>_r<round>.g<group>.log`: the bench lines of one launch. |
| 154 | + - `launches.tsv`: per launch, the status, seconds, row count, thermal status, host load |
| 155 | + average, and whether it was the first launch after an install. |
| 156 | + - `rounds.tsv`: per round, the lock wait, the round time, installs and launches. |
| 157 | + - `run.txt`: the APK hashes and filters used. |
| 158 | + |
| 159 | +### `table.py` |
| 160 | + |
| 161 | +``` |
| 162 | +table.py DIR[,DIR...] --anchor LABEL [--aa LABEL] [--labels A,B] [--metric median|min|norm] |
| 163 | + [--rows SUBSTR] [--md] |
| 164 | +``` |
| 165 | + |
| 166 | +The table shows the absolute medians and launch counts. Under them, for each label, it |
| 167 | +shows the within-round ratio to the anchor as median [min-max] over rounds. Flags: |
| 168 | + |
| 169 | +- `=` means the label's ratio range overlaps the A/A range, so it is indistinguishable |
| 170 | + from noise. |
| 171 | +- `*` means the ranges do not overlap. |
| 172 | +- `B` means the per-launch values look bimodal, so compare medians with care. |
| 173 | + |
| 174 | +`--metric norm` divides by the row's reference timing (callback rows time a reference |
| 175 | +callback in the same round). `--md` prints Markdown for a PR body. |
| 176 | + |
| 177 | +### `stat.sh` and `statsum.py` |
| 178 | + |
| 179 | +``` |
| 180 | +stat.sh --serial S --out DIR --labels "..." [--apk FILE] --rows FILE [--repeat N] [--events LIST] |
| 181 | +statsum.py DIR --anchor LABEL [--md] |
| 182 | +``` |
| 183 | + |
| 184 | +These count user-space instructions and cycles on the JS thread with `simpleperf stat`. |
| 185 | +Each row in `FILE` (`<key> <scale1> <scale2> <filter>`) runs at two scales. The difference |
| 186 | +cancels startup and every other fixed cost, and `statsum.py` divides it by the |
| 187 | +difference in the `ops` the bench reports for the row. The result is counts per |
| 188 | +operation of the row. Instruction counts resolve differences of a few instructions per |
| 189 | +op, far below what wall-clock times can show on a phone. Cycle counts are noisier. |
| 190 | + |
| 191 | +`stat.sh` needs an APK built with `--profileable`, on Android 10 (API 29) or later, and |
| 192 | +`simpleperf` on the device (`adb shell simpleperf --version`; if it is missing, push the |
| 193 | +NDK's `simpleperf/bin/android/<arch>/simpleperf`). Keep the events to what the CPU counts at |
| 194 | +once; `statsum.py` marks multiplexed counts `mux`. |
| 195 | + |
| 196 | +Example rows file: |
| 197 | + |
| 198 | +``` |
| 199 | +add 4 20 static.add(int,int) |
| 200 | +field 4 20 field.get int |
| 201 | +cb 4 20 callback.noArgs() |
| 202 | +``` |
| 203 | + |
| 204 | +## Benchmark rows |
| 205 | + |
| 206 | +The JNI bridge micro-benchmarks from #2092 are the default bench |
| 207 | +(`--bench jnibench`). They live in |
| 208 | +`test-app/app/src/main/assets/app/tests/benchmarks/jniBenchmarks.js`, with Java targets |
| 209 | +in `test-app/app/src/main/java/com/tns/tests/JniBench*.java`. They cover calls, field |
| 210 | +access, object creation and lifecycle, callbacks and contention. |
| 211 | + |
| 212 | +A bench named `X` follows this contract, so a branch can add its own without changing |
| 213 | +the harness: |
| 214 | + |
| 215 | +- `debug.ns.X=1` makes `boot.js` run the bench instead of the Jasmine suite. |
| 216 | +- `debug.ns.X.filter` holds `|`-separated substrings that select rows by name. |
| 217 | + `debug.ns.X.scale` multiplies the iterations. |
| 218 | +- Each row logs one `X_UPPER {json}` line through `console.log`, where `X_UPPER` is `X` in |
| 219 | + upper case. The JSON has at least `name` and `median` (ns per op), and optionally |
| 220 | + `min`, `ref` (a reference timing from the same rounds) and `ops`. `ops` is every |
| 221 | + operation the row executed in the launch, including warm-up and reference calls, and |
| 222 | + `stat.sh` needs it. |
| 223 | +- After the last row, the bench logs `X_UPPER_DONE`. |
| 224 | + |
| 225 | +To add rows to `jnibench`, add a `measureJs` or `measureCallback` entry to |
| 226 | +`buildBenchmarks()`. Keep each operation trivial, so the bridge dominates the |
| 227 | +measurement. |
| 228 | + |
| 229 | +**GC pitfall.** If a row times `gc()`, cross into Java once just before it, for example |
| 230 | +with a trivial static call. Some runtime state is released at the next JS-to-Java |
| 231 | +crossing. Without that crossing, the timed `gc()` also pays for releasing work left by |
| 232 | +earlier rows. |
| 233 | + |
| 234 | +## A new device |
| 235 | + |
| 236 | +The scripts are device-agnostic, but check these before trusting numbers from a new |
| 237 | +device: |
| 238 | + |
| 239 | +1. **Serial:** `adb devices -l`. Pass it as `--serial`, and give the device its own |
| 240 | + lock, which is the default `phone-<serial>.lock`. |
| 241 | +2. **First-launch behaviour:** run four or more rounds of `--labels "a=0 b=0" --no-discard`. |
| 242 | + Then the first launch after each install is measured, and `launches.tsv` marks it |
| 243 | + `first=1`. Rotation alternates which label gets it, so the `b`/`a` ratio in |
| 244 | + `table.py` swings round by round if first launches are slow. On the phone where this |
| 245 | + was found, the slowdown starts about 3.5 s into the process, so pick rows that run |
| 246 | + well past that. Keep the default discard |
| 247 | + either way; it is cheap insurance. |
| 248 | +3. **simpleperf:** `adb shell simpleperf --version`, and `getprop ro.build.version.sdk`. |
| 249 | + Below API 29 (for example a Galaxy S8 on Android 9), apps cannot be profileable, so |
| 250 | + `stat.sh` does not work with a release APK. Use wall-clock rounds only, or a rooted |
| 251 | + device. |
| 252 | +4. **Thermal and governor:** watch the thermal column of `launches.tsv`. Older phones |
| 253 | + throttle sooner, so lengthen `--gap` if later launches drift slower. |
| 254 | + |
| 255 | +Each experiment stays on one device. Two devices can run two independent experiments |
| 256 | +at once, one per lane, each with its own lock and output directory. |
0 commit comments