Catch performance regressions in Android and Kotlin code before they ship.
Mark a function with @PerformanceGuard. A Kotlin compiler plugin wraps it with a
low-overhead timer, your existing tests exercise it, and the build compares the measured
percentiles against a committed baseline. If p95 got 30 % slower, CI fails and names the
function.
class CardRepository(private val api: CardApi) {
@PerformanceGuard
suspend fun loadCards(ownerId: String): List<Card> = api.fetch(ownerId)
}$ ./gradlew performanceGuardCheck -PperformanceGuard=true
Performance Guard: FAIL
Status Function Change Detail
------ ------------------------------ ----------------------- -------------------------
PASS ProfileRepository#search P95 10.1ms → 10.2ms within thresholds
FAIL CardRepository#loadCards P95 20.2ms → 35.3ms P95 +74.8% (limit +25.0%)
PASS cards.shortTitle P95 2.1ms → 2.1ms within thresholds
Summary: 2 PASS, 1 FAIL
No code changes beyond the annotation, no manual timers, and nothing in builds where it's switched off: the bytecode is identical to a build without Performance Guard.
- How it works, end to end
- Add it to your app
- Daily use
- Configuration
- CI setup
- Measuring on a device
- What can be annotated
- Reading the results
- CLI (without Gradle)
- Modules
- Compatibility
- FAQ
- Building and releasing this project
1 @PerformanceGuard suspend fun loadCards(...) your code
│
├─ 2 KSP processor ─────► META-INF/performance-guard/<module>.json
│ (every guarded function, with a stable ID)
│
└─ 3 Kotlin IR plugin ──► body wrapped: start = site.enter()
try { original body }
catch { record failure; rethrow }
finally { site.exit(start, outcome) }
│
4 your unit tests / the app run ──────┘
│ runtime keeps a lock-free latency histogram per function
▼
5 raw-results-*.json (one file per test JVM or app process)
│
6 performanceGuardReport ──► merges all modules and processes
▼
build/performance-guard/performance-report.json (p50, p90, p95, p99, failures, …)
│
7 performanceGuardCheck ───► compares with performance-baseline.json (committed)
▼
PASS / WARNING / FAIL → exit code for CI
- You annotate functions whose speed matters: repository calls, parsing, screen loads.
- KSP (at compile time) records each guarded function in a small manifest and rejects
ones that can't be measured safely (inline, abstract,
@Composable, local). The manifest is how the report can list guarded functions that no test called. - The compiler plugin rewrites the function's IR. It runs before the Kotlin backend turns suspend functions into state machines, so the backend treats the wrapper like code you wrote by hand: return values, exceptions, coroutine suspension, thread switches and cancellation all behave exactly as before. Suspend functions are timed from call to final completion, including time suspended, which is what the caller waits for.
- The runtime is called twice per call (
enter/exit). It readsSystem.nanoTime(), bumps an atomic histogram bucket and a few counters. No allocation, no locks, no I/O, and it never throws into your code. Failures and coroutine cancellations are counted separately and kept out of the latency percentiles. - Results are written when the test JVM exits (or, on Android, periodically, when the app goes to the background, and on request). Histograms rather than averages are stored, because percentiles from several processes can't be averaged but histograms can be added.
- The report task merges every module's results into one report.
- The check task compares each function's percentiles with the committed baseline: a function fails when a percentile grew by more than its threshold and by more than an absolute noise floor, and only once it has enough samples on both sides.
The design document, with the reasoning behind each decision, is in architecture.md.
Performance Guard is published on JitPack today. (Maven Central coordinates are
io.github.manihq.performanceguard:*; see releasing.)
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
maven("https://jitpack.io")
}
resolutionStrategy {
eachPlugin {
// JitPack serves the plugin as a regular artifact, so map the plugin ID to it.
if (requested.id.id == "io.github.manihq.performance-guard") {
useModule("com.github.manihq.performance-guard:performance-guard-gradle-plugin:${requested.version}")
}
}
}
}
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven("https://jitpack.io")
}
}Apply the plugin once, in the root project. Keep your Kotlin plugin declared in the same
plugins block (as Android Studio's templates already do).
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.kotlin.android) apply false // Kotlin 2.0.21
id("io.github.manihq.performance-guard") version "v0.1.0"
}
performanceGuard {
variants.set(setOf("debug")) // Android variants to instrument
}Every module that uses Kotlin (Android app, Android library or plain JVM) is configured automatically. The plugin adds, per module:
| Always | Only when enabled |
|---|---|
performance-guard-annotations as compileOnly (nothing ships) |
KSP + the Performance Guard processor |
| the compiler plugin, for the configured variants | |
performance-guard-runtime (+ -runtime-android on Android) for those variants |
|
| a results folder for each matching unit-test task |
You don't add any of these dependencies yourself.
import io.github.manihq.performanceguard.PerformanceGuard
class ProfileRepository(private val dao: ProfileDao) {
@PerformanceGuard
fun search(query: String): List<Profile> = dao.search(query)
}Any unit test works. Performance Guard measures whatever runs; the test doesn't need to know.
class ProfileSearchTest {
@Test
fun search() {
val repository = ProfileRepository(FakeProfileDao(profiles = 5_000))
repeat(50) { assertTrue(repository.search("smith").isNotEmpty()) }
}
}Call each guarded function at least minimumSamples times (30 by default). Below that,
the check reports INSUFFICIENT_DATA instead of guessing.
./gradlew performanceGuardUpdateBaseline -PperformanceGuard=true
git add performance-baseline.jsonThat's it. From now on:
./gradlew performanceGuardCheck -PperformanceGuard=trueruns the instrumented tests, builds the report and compares it with the baseline.
| Task | What it does |
|---|---|
performanceGuardReport |
Runs the instrumented tests and writes build/performance-guard/performance-report.json |
performanceGuardCheck |
Report + compare with the baseline; fails the build on a regression |
performanceGuardUpdateBaseline |
Report + overwrite performance-baseline.json |
performanceGuardPullDeviceResults |
Flush and adb pull results from the app on a device |
All of them need -PperformanceGuard=true (or performanceGuard { enabled.set(true) }).
Without it, Performance Guard does nothing and adds nothing.
When a check fails: look at the function it names. If the slowdown is expected (a feature that genuinely does more work), update the baseline in the same pull request, so the change is reviewed like any other. If not, you found a regression before it shipped.
All settings live in the root project:
performanceGuard {
enabled.set(true) // default: -PperformanceGuard=true, otherwise false
variants.set(setOf("debug", "benchmark")) // Android variants to instrument (default: debug)
allowReleaseInstrumentation.set(false) // refuse variants named "*release*" (default)
samplingRate.set(1.0) // fraction of calls measured
tracing.set(false) // Perfetto/systrace sections on Android
bufferCapacity.set(0) // >0 also keeps raw samples (DROP_NEWEST/DROP_OLDEST)
bufferOverflow.set("DROP_NEWEST")
baselineFile.set(file("performance-baseline.json"))
thresholds.set(mapOf("p50" to 0.10, "p95" to 0.15)) // allowed growth per percentile
warnAt.set(0.5) // WARNING above half of a threshold
minimumSamples.set(30) // fewer samples never fail
noiseFloorMillis.set(1.0) // ignore changes smaller than this
failOnRegression.set(true)
devicePackage.set("com.example.app") // for performanceGuardPullDeviceResults
}Per-function, you can give a fixed ID that survives renames and moves:
@PerformanceGuard(name = "cards.sync")
suspend fun syncCards(request: SyncRequest): SyncResultWithout a name, the ID is derived from the declaration, e.g.
com.example.cards.CardRepository#syncCards(com.example.cards.SyncRequest).
Renaming the function or changing parameter types gives it a new ID (reported as NEW and
REMOVED, never as a failure).
Any CI that runs Gradle works. GitHub Actions example:
name: performance
on: pull_request
jobs:
performance:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with: { distribution: temurin, java-version: 17 }
- uses: gradle/actions/setup-gradle@v4
- run: ./gradlew performanceGuardCheck -PperformanceGuard=true
- if: always()
uses: actions/upload-artifact@v4
with:
name: performance-guard
path: build/performance-guard/Tips for stable numbers:
- Record the baseline on the same kind of machine that runs the check. Each result file
includes an environment fingerprint (JVM/ART version, CPU architecture, device model, API
level). If it differs from the baseline's, the check reports
ENV_MISMATCHand doesn't fail, rather than comparing a laptop with a CI runner. - Update the baseline from
mainafter merges, or in the PR that intentionally changes speed. - Guard functions that take at least a few hundred microseconds. For very fast, very hot
functions use
samplingRate, or a microbenchmark instead. - Run JVM unit tests where possible: they need no device and are the least noisy.
For instrumented builds, the app writes results to
/sdcard/Android/media/<applicationId>/performance-guard/ (no permissions needed). They're
flushed every 10 seconds, when the app goes to the background, and when a test asks:
./gradlew :app:installDebug -PperformanceGuard=true
# ...drive the app: instrumented tests, Macrobenchmark, or by hand...
./gradlew performanceGuardPullDeviceResults performanceGuardCheck -PperformanceGuard=trueperformanceGuardPullDeviceResults sends
adb shell am broadcast -a io.github.manihq.performanceguard.FLUSH -p <package> and pulls the
files into the root build folder, where the report picks them up.
With tracing.set(true), every guarded call also shows up in Perfetto as a PG:<name>
section (async sections for suspend functions, API 29+).
| Supported | Not supported (compile error explains why) |
|---|---|
| Functions in classes, objects and companion objects | inline functions |
| Top-level and extension functions | @Composable functions |
suspend functions |
abstract, interface, expect and external functions |
| Generic functions, default arguments, overloads | local functions and lambdas |
Any return type, including Nothing, Unit, Result<T> |
constructors and property accessors |
Composables are rewritten by the Compose compiler in ways that a try/finally would
interfere with. Use Macrobenchmark and Compose tracing for UI performance.
performance-report.json (schema v1) contains, per function: invocations, sampled calls,
failures, cancellations, min, max, mean, p50, p90, p95, p99 and the merged histogram, plus
notExercised (guarded functions no test called), warnings and the environment.
Check statuses:
| Status | Meaning | Fails the build |
|---|---|---|
PASS |
Within thresholds, or the change is below the noise floor | no |
WARNING |
Grew by more than warnAt × threshold |
no |
FAIL |
Grew by more than the threshold and more than the noise floor | yes |
INSUFFICIENT_DATA |
Fewer than minimumSamples on either side |
no |
NEW |
Not in the baseline yet | no |
REMOVED |
In the baseline, not measured now | no |
ENV_MISMATCH |
Measured on a different environment than the baseline | no |
Errors found while merging (for example the same ID declared in two modules) also fail the check, because they would make the comparison meaningless.
Accuracy: durations are bucketed with at most ±1.6 % error; min, max and mean are exact. Baseline and current runs are bucketed the same way, so thresholds of 5 % and up are unaffected.
The same report and comparison logic ships as a standalone jar:
java -jar performance-guard-cli-<version>-all.jar report \
--results path/to/raw-results/ --manifests path/to/build/generated/ksp --out report.json
java -jar performance-guard-cli-<version>-all.jar compare \
--report report.json --baseline performance-baseline.json --threshold p95=0.15
java -jar performance-guard-cli-<version>-all.jar baseline --report report.json --out performance-baseline.jsonExit codes: 0 pass (warnings allowed), 1 regression, 2 usage error, 3 invalid input.
| Artifact | What it is | Who uses it |
|---|---|---|
performance-guard-gradle-plugin |
Plugin io.github.manihq.performance-guard; wires everything below |
You (the only thing you apply) |
performance-guard-annotations |
@PerformanceGuard |
Added compileOnly by the plugin |
performance-guard-compiler |
Kotlin K2 compiler plugin (IR instrumentation) | Kotlin compiler |
performance-guard-ksp |
KSP processor writing the module manifest | KSP |
performance-guard-ids |
Stable ID format shared by KSP and the compiler plugin | Both of the above |
performance-guard-runtime |
JVM runtime: histograms, sampling, results files | Instrumented code |
performance-guard-runtime-android |
Android setup: output folder, device info, flushing, tracing | Instrumented Android variants |
performance-guard-report |
Report, baseline and comparison engine | Gradle plugin, CLI |
performance-guard-cli |
Command-line front end for the report engine | Non-Gradle CI |
The sample/ folder is a multi-module project (card, profile and dashboard feature
modules plus an Android Compose app) that consumes the plugin like a real app. CI runs it end to end on every commit:
it records a baseline, checks that unchanged code passes, and checks that an injected
15 ms slowdown fails.
| Version | |
|---|---|
| Kotlin | 2.0.21 (K2). Compiler plugins are tied to the Kotlin version they're built for. |
| KSP | 2.0.21-1.0.28 (applied by the plugin if your module doesn't already use KSP) |
| Android Gradle Plugin | 8.x |
| Gradle | 8.x |
| Android minSdk | 21 |
| JDK | 17 to build; the runtime targets Java 11 bytecode |
Is this a replacement for Macrobenchmark? No. Macrobenchmark measures whole user journeys (startup, scrolling, frame timing) from outside the app on a real device. Performance Guard measures individual functions from inside, during tests you already run, so it's cheap enough to gate every pull request. Macrobenchmark scenarios are a good way to exercise guarded functions on a device.
Is the baseline the same as a Baseline Profile? No. A Baseline Profile is an ahead-of-time compilation hint that makes code faster. A Performance Guard baseline is a record of how fast your code was, to compare against.
What does it cost at run time?
In builds where it's disabled: nothing (identical bytecode, no runtime dependency). When
enabled: two nanoTime calls and a few atomic increments per measured call, no allocation.
That's negligible for functions that do real work (I/O, parsing, database), and the reason
to avoid annotating tiny functions called millions of times.
Can it end up in my release build?
Only if you ask for it. Instrumentation is off unless enabled, variants named *release*
are refused unless allowReleaseInstrumentation is set, and enabling it is meant for
performance runs (-PperformanceGuard=true), not regular builds. Note that plain JVM modules
are instrumented whenever Performance Guard is enabled, since they have no variants.
Why histograms instead of storing every sample?
They have a fixed size, can be updated without locks, and merge exactly across processes,
modules and devices. Raw samples are available via bufferCapacity if you need them.
./gradlew build # compile and test all modules
./gradlew -p sample performanceGuardCheck -PperformanceGuard=true # end-to-end sampleJitPack builds any tag on request (jitpack.yml runs publishToMavenLocal), so pushing a
tag such as v0.1.0 is a release.
Maven Central: pushing a v* tag runs .github/workflows/release.yml, which publishes
io.github.manihq.performanceguard:* and the plugin marker. It needs a verified
io.github.manihq namespace on the Central Portal and four repository secrets:
MAVEN_CENTRAL_USERNAME, MAVEN_CENTRAL_PASSWORD, SIGNING_KEY, SIGNING_KEY_PASSWORD.
Once published there, consumers can drop JitPack and the resolutionStrategy block and use
id("io.github.manihq.performance-guard") version "0.1.0" directly.
MIT