diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/jniBenchmarks.js b/test-app/app/src/main/assets/app/tests/benchmarks/jniBenchmarks.js index 6465464f9..cd1d50a10 100644 --- a/test-app/app/src/main/assets/app/tests/benchmarks/jniBenchmarks.js +++ b/test-app/app/src/main/assets/app/tests/benchmarks/jniBenchmarks.js @@ -21,7 +21,9 @@ function median(values) { return sorted[Math.floor(sorted.length / 2)]; } -function report(name, nsPerOp, refNsPerOp) { +// ops, when given, is every operation the row executed in this launch (warm-up, reference +// calls and timed rounds): tools/perf/stat.sh divides counter deltas between two scales by it. +function report(name, nsPerOp, refNsPerOp, ops) { var result = { name: name, median: Math.round(median(nsPerOp) * 10) / 10, @@ -31,6 +33,9 @@ function report(name, nsPerOp, refNsPerOp) { result.ref = Math.round(median(refNsPerOp) * 10) / 10; result.refMin = Math.round(Math.min.apply(null, refNsPerOp) * 10) / 10; } + if (ops) { + result.ops = ops; + } console.log("JNIBENCH " + JSON.stringify(result)); return result; } @@ -39,7 +44,8 @@ function report(name, nsPerOp, refNsPerOp) { function measureJs(name, iterations, body) { if (skipped(name)) return null; iterations *= SCALE; - var sink = body(Math.max(1000, iterations >> 2)); + var warmup = Math.max(1000, iterations >> 2); + var sink = body(warmup); var samples = []; for (var r = 0; r < ROUNDS; r++) { var start = performance.now(); @@ -48,7 +54,7 @@ function measureJs(name, iterations, body) { samples.push((elapsed * 1e6) / iterations); } globalThis.__jniBenchSink = sink; - return report(name, samples); + return report(name, samples, null, warmup + ROUNDS * iterations); } // Callback rows drift with the device's performance state independently of the other rows, @@ -65,8 +71,9 @@ function measureCallback(name, cb, kind, iterations) { if (refCallback === null) { refCallback = new JniBench.Callback({ twoInts: function (a, b) { } }); } + var warmup = Math.max(1000, iterations >> 2); JniBench.runCallbacks(refCallback, REF_CALLBACK_KIND, refIterations >> 2); - JniBench.runCallbacks(cb, kind, Math.max(1000, iterations >> 2)); + JniBench.runCallbacks(cb, kind, warmup); var samples = []; var ref = []; for (var r = 0; r < ROUNDS; r++) { @@ -74,7 +81,7 @@ function measureCallback(name, cb, kind, iterations) { var nanos = JniBench.runCallbacks(cb, kind, iterations); samples.push(Number(nanos) / iterations); } - return report(name, samples, ref); + return report(name, samples, ref, (refIterations >> 2) + warmup + ROUNDS * (refIterations + iterations)); } diff --git a/test-app/runtime/CMakeLists.txt b/test-app/runtime/CMakeLists.txt index 6a792c596..3a134ddfc 100644 --- a/test-app/runtime/CMakeLists.txt +++ b/test-app/runtime/CMakeLists.txt @@ -13,6 +13,15 @@ if (CCACHE_FOUND AND (USE_CCACHE)) set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache) endif (CCACHE_FOUND AND (USE_CCACHE)) +# Benchmark builds only (tools/perf): BenchVariant.h reads debug.ns.benchvariant +# at load time so one APK can carry every label of an A/B. Never enable it for a +# build that ships. +option(NS_BENCH_VARIANTS "Read the run-time benchmark variant from debug.ns.benchvariant" OFF) +if (NS_BENCH_VARIANTS) + MESSAGE(STATUS "## NS_BENCH_VARIANTS is ON: benchmark build, do not ship") + add_definitions(-DNS_BENCH_VARIANTS) +endif () + # Command info: https://cmake.org/cmake/help/v3.4/command/message.html # we pass the android_ndk_root from gradle because for some reason # "-DANDROID_STL=c++_static" is just not enough for clang++ to find some libraries in the ndk diff --git a/test-app/runtime/build.gradle b/test-app/runtime/build.gradle index 16a6951e0..fd4e5c4cb 100644 --- a/test-app/runtime/build.gradle +++ b/test-app/runtime/build.gradle @@ -24,11 +24,18 @@ if (onlyX86) { println "OnlyX86 build triggered." } -def useCCache = project.hasProperty("useCCache") +// -PuseCCache (CI and packaging), its -PuseCcache spelling, or NS_USE_CCACHE=1 in the environment. +def useCCache = project.hasProperty("useCCache") || project.hasProperty("useCcache") || + System.getenv("NS_USE_CCACHE") == "1" if (useCCache) { println "Use CCache build triggered." } +def benchVariants = project.hasProperty("benchVariants") +if (benchVariants) { + println "Benchmark variant switch (NS_BENCH_VARIANTS) enabled: do not ship this build." +} + def defaultNdkVersion = "29.0.14206865" @@ -120,6 +127,10 @@ android { arguments.add("-DUSE_CCACHE=true") } + if (benchVariants) { + arguments.add("-DNS_BENCH_VARIANTS=ON") + } + cppFlags "-std=c++20" arguments "-DANDROID_STL=c++_static", "-DANDROID_NDK_ROOT=${NDK_PATH}", "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON" } diff --git a/test-app/runtime/src/main/cpp/BenchVariant.h b/test-app/runtime/src/main/cpp/BenchVariant.h new file mode 100644 index 000000000..d233ec5b7 --- /dev/null +++ b/test-app/runtime/src/main/cpp/BenchVariant.h @@ -0,0 +1,43 @@ +#ifndef BENCHVARIANT_H_ +#define BENCHVARIANT_H_ + +// Run-time variant switch for benchmark builds (tools/perf/README.md). +// +// Configured with -PbenchVariants (CMake NS_BENCH_VARIANTS=ON), the runtime +// reads the system property debug.ns.benchvariant once, when the library +// loads, so one APK can carry every label of an A/B as +// `if (BenchVariant() == N)` branches. Without the option BenchVariant() is a +// constant 0: the branches fold away and the property is never read. + +#ifdef NS_BENCH_VARIANTS +#include + +#include +#endif + +namespace tns { + +#ifdef NS_BENCH_VARIANTS + +inline int g_benchVariant = 0; + +inline int BenchVariant() { return g_benchVariant; } + +// Called once from JNI_OnLoad, before any runtime exists. +inline void InitBenchVariant() { + char value[PROP_VALUE_MAX] = {0}; + __system_property_get("debug.ns.benchvariant", value); + g_benchVariant = static_cast(std::strtol(value, nullptr, 10)); +} + +#else + +constexpr int BenchVariant() { return 0; } + +inline void InitBenchVariant() {} + +#endif + +} // namespace tns + +#endif // BENCHVARIANT_H_ diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index 77e70b9d9..9749ac582 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -12,6 +12,7 @@ #include #include "ArgConverter.h" +#include "BenchVariant.h" #include "BuiltinLoader.h" #include "CallbackHandlers.h" #include "Constants.h" @@ -99,6 +100,13 @@ void Runtime::Init(JavaVM* vm, void* reserved) { NATIVE_SCRIPT_RUNTIME_VERSION, NATIVE_SCRIPT_RUNTIME_COMMIT_SHA); +#ifdef NS_BENCH_VARIANTS + InitBenchVariant(); + // tools/perf checks this line to reject a launch that ran the wrong variant. + __android_log_print(ANDROID_LOG_INFO, "TNS.Runtime", "NS_BENCH_VARIANT=%d", + BenchVariant()); +#endif + if (Runtime::s_jvm == nullptr) { s_jvm = vm; @@ -1044,6 +1052,11 @@ Isolate* Runtime::PrepareV8Runtime(const string& filesPath, globalTemplate->Set( ArgConverter::ConvertToV8String(isolate, "__time"), FunctionTemplate::New(isolate, CallbackHandlers::TimeCallback)); +#ifdef NS_BENCH_VARIANTS + globalTemplate->Set(ArgConverter::ConvertToV8String(isolate, "__benchVariant"), + v8::Integer::New(isolate, BenchVariant()), + readOnlyFlags); +#endif // queueMicrotask(callback) per spec: // https://developer.mozilla.org/en-US/docs/Web/API/Window/queueMicrotask diff --git a/tools/perf/README.md b/tools/perf/README.md new file mode 100644 index 000000000..5db2738fe --- /dev/null +++ b/tools/perf/README.md @@ -0,0 +1,256 @@ +# Runtime performance tooling + +Scripts for A/B benchmarks of the Android runtime on a real device: build one benchmark +APK, run labelled rounds under a device lock, and turn the logs into a ratio table. +They use bash and python3 only. Run them with `bash`, even from zsh. + +```bash +OUT=/tmp/ns-perf/my-experiment +# 1. one release APK that carries every label (variants 0, 1, 2 below) +bash tools/perf/build.sh --out "$OUT/apks" --label exp --variants --ccache +# 2. rounds on one device: base and its A/A copy base2 both run variant 0 +bash tools/perf/run.sh --serial --out "$OUT/runs" --apk "$OUT/apks/exp.apk" \ + --labels "base=0 base2=0 cache=1 nocache=2" --rounds 6 \ + --filter 'static.noop()|field.get int|callback.noArgs()' +# 3. the table +python3 tools/perf/table.py "$OUT/runs" --anchor base --aa base2 +``` + +## The protocol, and why + +Each rule below cost a wrong result at least once. + +- **Release, optimized APK only.** The debug runtime is built `-O0` and debuggable apps + run with CheckJNI. `build.sh` builds `:app:assembleRelease -Poptimized` signed with the + debug keystore, because shipped apps use the optimized runtime. +- **Install, then `cmd package compile -m speed -f`, then throw away the first launch.** + On some phones the first launch after an install runs about 1.6x slower from about + 3.5 s into the process, on every row. `run.sh` installs once per round (once per APK in a + round, if labels use separate APKs), speed-compiles, runs one discarded launch + (`--discard-secs`, default 8 s), and measures only relaunches. +- **Every label runs in every round, in rotated order.** Ratios are taken within a round + (`table.py`), because absolute times swing between launches by core and frequency + state. Rotation keeps a label from always running first or last. +- **An A/A label.** It is a second label with the anchor's exact configuration. Its + ratio range is the noise floor, and `table.py --aa` compares every other range against it. +- **One device per experiment.** `run.sh` records the serial in `/device.txt` and + refuses to add rounds from another device to the same directory. +- **No builds while measuring.** A concurrent gradle build once inflated every row by + 50% (on an emulator, which shares the host's CPU). `launches.tsv` records the host's + load average and the device's thermal status for every launch, so you can check. + +## Run-time variants (`--variants`) + +Building one APK per label is slow. It also leaves several APKs that each need an +install, a speed compile and a discarded launch every round. Instead, a benchmark build +can carry every label as a run-time branch: + +- `build.sh --variants` passes `-PbenchVariants`, which sets the CMake option + `NS_BENCH_VARIANTS` (off by default). The runtime then reads the system property + `debug.ns.benchvariant` (an integer, default 0) once, when `libNativeScript.so` loads. +- C++: `#include "BenchVariant.h"`, then `if (tns::BenchVariant() == 1) { ... }`. + The accessor is an inline read of a process global. Without the option it is + `constexpr 0`, so the branches compile away and nothing reads the property. +- JS: `globalThis.__benchVariant`, a read-only number. It is `undefined` without the + option, so use `(globalThis.__benchVariant | 0)`. +- Java can read the property itself (`getprop debug.ns.benchvariant`); the test app's + `JniBench.getProp` shows how. +- `run.sh` sets the property before each launch. The runtime logs + `NS_BENCH_VARIANT=` at startup, and `run.sh` checks it against the label. A + mismatch marks the launch `wrong-variant` and keeps its log as `*.log.bad`. A missing + line aborts the run, because the APK was built without `--variants`. + +**Convention.** Variant branches live in local, bench-only commits on top of the change +under test, and are never pushed. Variant 0 is the code as it would ship. Each other +number is one alternative, and the A/A label also uses 0. + +**Caveat: one binary, one code layout.** Every variant shares the same compiled code. +An alternative whose effect depends on code layout, inlining or I-cache footprint +(adding a large function, moving a hot loop) can measure differently once it is the +only code path. The A/A pair catches noise, not layout. Confirm a layout-sensitive +result, or any result you will publish, with separate APKs: one `build.sh` per side, run +as `base=base.apk base2=base.apk new=new.apk`. Build both sides with the same `--ccache` +setting. A ccache build rewrites source paths (`__FILE__`), so it is not byte-identical +to a build without ccache. + +## ccache (`--ccache`) + +`--ccache` builds through ccache with settings that share cache entries across +checkouts. The runtime's existing switch accepts `-PuseCCache` (used by CI and +packaging), `-PuseCcache`, or `NS_USE_CCACHE=1` in the environment. `build.sh` also sets: + +| variable | value | why | +|---|---|---| +| `CCACHE_DIR` | `$NS_PERF_CCACHE_DIR`, else `~/Library/Caches/ns-android-ccache` | a dedicated cache, so unrelated projects don't evict runtime objects | +| `CCACHE_MAXSIZE` | `$NS_PERF_CCACHE_MAXSIZE`, else `3G` | one arm64 configuration takes about 25 MB, so 3 GB holds many | +| `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 | +| `CCACHE_NOHASHDIR` | `1` | `-g` makes ccache hash the working directory by default, which differs per checkout | + +Measured on an M-series Mac with a host load average of about 8 (arm64, +`-Poptimized --variants`, whole `build.sh` wall time): + +| build | wall time | ccache | +|---|---:|---| +| first build in a fresh worktree, empty cache | 28 s | 79 misses | +| first build in a second worktree (different path), same sources | 18 s | 79/79 hits | +| same worktree, native build state deleted, no ccache | 22 s | — | +| same worktree, native build state deleted, warm cache | 12 s | 79/79 hits | + +The rest of a build (gradle, Java, dex, packaging) is not cached, and a build that only +changes JS or Java reuses the native objects anyway. ccache pays off in fresh worktrees, +after switching a CMake flag (`-Poptimized`, `--variants`), each of which recompiles +everything, and on a busy host, where native compilation slows the most. +`ccache -s` with the same `CCACHE_DIR` shows totals. + +## Device lock and device selection + +Several sessions share each device, so every command that touches one holds a lock +for its whole session. `run.sh` takes it per round, so other sessions can interleave +between rounds. + +- **The lock** is a directory created with `mkdir`. It is + `$NS_PERF_LOCK`, or `--lock PATH`, or else + `${NS_PERF_LOCK_DIR:-~/.cache/ns-perf/locks}/phone-.lock`. To share an + existing lock with other tools, point `NS_PERF_LOCK` (or `--lock`) at the same path. + The holder writes an `owner` file inside the lock, and waiters print it. +- **Cleanup happens only while the lock is held.** That covers force-stopping the app + and clearing the `debug.ns.*` properties. A process that is still waiting, or that is + interrupted while waiting, touches nothing. A stale lock is never broken + automatically: check `owner` and remove it by hand. +- **`--serial` is required.** The scripts never pick a device for you. Serials in + `NS_PERF_PROTECTED_SERIALS` (default `emulator-5554`) are refused outright. + +## Commands + +### `build.sh` + +``` +build.sh --out DIR [--label NAME] [--variants] [--ccache] [--profileable] [--regular] + [--abi ABI] [--repo DIR] [--keep-build] +``` + +This builds `DIR/