Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ let package = Package(
linkerSettings: [
.linkedLibrary("z")
]
),
.testTarget(
name: "CallstackPerformanceAnalyticsTests",
dependencies: ["CallstackPerformanceAnalytics"]
)
]
)
47 changes: 45 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ pod 'CallstackPerformanceAnalytics', :path => '../node_modules/@callstack/perfor
### iOS with Swift Package Manager

In Xcode, add `https://github.com/callstackincubator/performance-analytics.git` as a
package dependency, select version `0.1.0`, and link the `CallstackPerformanceAnalytics`
package dependency, select version `0.2.0`, and link the `CallstackPerformanceAnalytics`
product to the app target. Xcode and CI need read access to the private repository.

### Android with Gradle
Expand Down Expand Up @@ -243,7 +243,7 @@ it for you. Gradle also resolves the SDK's C++ dependency.

```kotlin
dependencies {
implementation("com.callstack:performance-analytics-android:0.1.0")
implementation("com.callstack:performance-analytics-android:0.2.0")
}
```

Expand All @@ -267,6 +267,49 @@ but uploads only completed sessions from previous app processes. Restart the
app and flush to send a completed session. The server commits sessions before
acknowledging them and deduplicates retries by project and session ID.

### Thread benchmarks

React Native and React Nitro export `ThreadBenchmark` on Android and iOS.
Import it from the adapter your app uses. Swift apps can construct
`try ThreadBenchmark(name:)` from `CallstackPerformanceAnalytics`. Kotlin apps
use `com.callstack.performanceanalytics.ThreadBenchmark` on any app thread.
Each instance starts a named window and returns its result once, on the thread
that created it. Opening a window opts into the hardware counters. The API
can run independently of analytics setup, sampling and upload.

```kotlin
val window = ThreadBenchmark("decode")
try {
decode()
} finally {
val result = window.end()
reportToCI(result)
}
```

| Field | Meaning |
| --- | --- |
| `name`, `threadId` | Window name and OS thread ID of the caller. |
| `elapsedMs` | Monotonic wall time including waits within this window. |
| `threadCpuMs` | CPU time consumed by this thread, from `CLOCK_THREAD_CPUTIME_ID`. The telemetry field `cpuTotalTimeMs` covers the whole process. |
| `instructions`, `cycles` | Raw retired instructions and CPU cycles for user-space execution on this thread. Both events share one Linux perf group. |
| `countersAvailable` | True when the group supplied counts with positive running time. |
| `timeEnabledNs`, `timeRunningNs` | Android kernel-reported enabled and scheduled time. Equal positive values mean full coverage. A smaller running time means partial coverage. Counts are unscaled. |
| `counterErrno` | Platform error number when the counters are unavailable. The clocks remain available. |

Unavailable hardware values are nullable on Android and optional in JavaScript.
A group scheduled for zero time reports its coverage and omits both counts.
Each participating thread needs its own window. Use a separate monotonic timer
from dispatch to completion for the duration of a multi-thread action.
On iOS, both adapters return the Darwin thread ID and the two clocks.
`countersAvailable` is false and `counterErrno` is `ENOTSUP`. The in-app
result omits instructions, cycles and counter coverage. XCTest can separately
collect CPU metrics for a performance-test block on its calling thread.
[Apple’s XCTCPUMetric](https://developer.apple.com/documentation/xctest/xctcpumetric)

[React Native Release example](apps/example-react-native/benchmarks) ·
[Android instrumentation and CI invocation](apps/example-react-nitro/benchmarks/README.md)

## Development

```sh
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import CryptoKit
import XCTest

final class ThreadBenchmarkPerformanceTests: XCTestCase {
func testSHA256OnCallingThread() throws {
let input = Data(repeating: 0, count: 8 * 1024 * 1024)
let cpu = XCTCPUMetric(limitingToCurrentThread: true)
let clock = XCTClockMetric()
var digest: SHA256.Digest?

measure(metrics: [cpu, clock]) {
digest = SHA256.hash(data: input)
}

let hash = try XCTUnwrap(digest)
let bytes = Data(hash)
let checksum = bytes.base64EncodedString()
XCTAssertEqual(checksum, "La6x82CVtEsxhBCz9Oi12Yncx7sCPRQmxJLasKMFPnQ=")
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import CallstackPerformanceAnalytics
import Darwin
import XCTest

final class ThreadBenchmarkTests: XCTestCase {
func testWindowStaysOnItsOpeningThread() throws {
var ownerID: UInt64 = 0
let status = pthread_threadid_np(nil, &ownerID)
XCTAssertEqual(status, 0)
let owner = try ThreadBenchmark(name: "owner")
let finished = expectation(description: "worker window ended")

Thread.detachNewThread {
defer { finished.fulfill() }
do {
XCTAssertThrowsError(try owner.end())
var tid: UInt64 = 0
let status = pthread_threadid_np(nil, &tid)
XCTAssertEqual(status, 0)
let worker = try ThreadBenchmark(name: "worker")
let result = try worker.end()
XCTAssertEqual(result.threadId, tid)
XCTAssertFalse(result.countersAvailable)
XCTAssertEqual(result.counterErrno, ENOTSUP)
} catch {
XCTFail(error.localizedDescription)
}
}

wait(for: [finished], timeout: 5)
let result = try owner.end()
XCTAssertEqual(result.name, "owner")
XCTAssertEqual(result.threadId, ownerID)
XCTAssertGreaterThan(result.elapsedMs, 0)
XCTAssertGreaterThan(result.threadCpuMs, 0)
XCTAssertThrowsError(try owner.end())
}
}
33 changes: 33 additions & 0 deletions apps/example-react-native/benchmarks/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# React Native thread benchmark

The benchmark entry runs a checksum on the Hermes JS thread and displays the
JSON result as accessible text. It works before analytics setup. Android
reports PMU counts when the device permits them. iOS reports elapsed time,
thread CPU time, the Darwin TID and `countersAvailable: false`.

From the example's Android directory, build the benchmark entry into a Release
APK with `ENTRY_FILE=benchmarks/index.js ./gradlew :app:assembleRelease`.
For iOS, run `yarn example ios:setup` from the repository root, then build the
example Xcode project in Release with the `ENTRY_FILE=benchmarks/index.js`
build setting. Launch the resulting app to read the recorded window.

For an iOS XCTest performance test running work directly on the test thread,
`XCTCPUMetric(limitingToCurrentThread: true)` records CPU time, cycles and retired
instructions in the test result bundle on supported hardware. A block that
dispatches work to Hermes measures the dispatching thread. The example above
opens its window inside Hermes to measure the JavaScript thread itself.
[Apple's XCTCPUMetric](https://developer.apple.com/documentation/xctest/xctcpumetric)

The package test `ThreadBenchmarkPerformanceTests/testSHA256OnCallingThread`
measures SHA-256 over 8 MiB in XCTest. To collect its available metrics in CI,
run from the repository root with a test device selected:

```sh
xcodebuild -scheme CallstackPerformanceAnalytics -configuration Release \
-destination "id=$DEVICE_UDID" -resultBundlePath Benchmark.xcresult \
-only-testing:CallstackPerformanceAnalyticsTests/ThreadBenchmarkPerformanceTests test
xcrun xcresulttool get test-results metrics --path Benchmark.xcresult
```

Inspect the returned metric identifiers before comparing runs. The iOS 27.0
simulator used for this PR returned only the monotonic clock metric.
17 changes: 17 additions & 0 deletions apps/example-react-native/benchmarks/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import React from 'react';
import { AppRegistry, Text } from 'react-native';
import { ThreadBenchmark } from '@callstack/performance-analytics-react-native';
import { name } from '../app.json';

const window = new ThreadBenchmark('hermes-checksum');
let checksum = 0;
for (let i = 0; i < 1_000_000; i++) checksum += i;
const result = window.end();
if (checksum !== 499999500000) throw new Error('Incorrect Hermes checksum');
const report = JSON.stringify(result);

function BenchmarkResult() {
return React.createElement(Text, { accessibilityLabel: report }, report);
}

AppRegistry.registerComponent(name, () => BenchmarkResult);
17 changes: 17 additions & 0 deletions apps/example-react-nitro/android/app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ plugins {
id("com.margelo.reactnitro")
}

val benchmarkAssets = layout.buildDirectory.dir("benchmark/assets")

android {
namespace = "com.example.perfkitexample"
compileSdk = 36
Expand All @@ -12,9 +14,12 @@ android {
applicationId = "com.example.perfkitexample"
minSdk = 26
targetSdk = 36
testInstrumentationRunner = "com.example.perfkitexample.BenchmarkInstrumentation"
versionCode = 1
versionName = "1.0"
}
testBuildType = "release"
sourceSets["androidTest"].assets.srcDir(benchmarkAssets)
signingConfigs {
getByName("debug") {
storeFile = file("debug.keystore")
Expand All @@ -38,4 +43,16 @@ android {
dependencies {
val runtime = project(":runtime")
implementation(runtime)
val androidSdk = project(":performance-analytics-android")
androidTestImplementation(androidSdk)
}

val bundleThreadBenchmark = tasks.register<Exec>("bundleThreadBenchmark") {
val exampleDirectory = rootProject.file("..")
workingDir(exampleDirectory)
val output = benchmarkAssets.get().asFile
commandLine("bun", "benchmarks/bundle.ts", output.absolutePath)
}
tasks.matching { it.name == "mergeReleaseAndroidTestAssets" }.configureEach {
dependsOn(bundleThreadBenchmark)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package com.example.perfkitexample

import android.app.Activity
import android.app.Instrumentation
import android.content.pm.ApplicationInfo
import android.os.Bundle
import android.os.Process
import android.os.SystemClock
import android.util.Base64
import com.callstack.performanceanalytics.ThreadBenchmark
import com.margelo.reactnitro.runtime.JSRuntime
import org.json.JSONObject
import java.security.MessageDigest
import java.util.concurrent.Callable
import java.util.concurrent.Executors
import java.util.concurrent.FutureTask

/** am instrument -w -e workerBlocks 32 ... returns one JSON record. */
class BenchmarkInstrumentation : Instrumentation() {
private val block = ByteArray(256 * 1024)
private var workerBlocks = 32

override fun onCreate(arguments: Bundle?) {
super.onCreate(arguments)
val requested = arguments?.getString("workerBlocks")
if (requested != null) workerBlocks = requested.toInt()
require(workerBlocks > 0)
start()
}

override fun onStart() {
val output = Bundle()
try {
val flags = targetContext.applicationInfo.flags
check(flags and ApplicationInfo.FLAG_DEBUGGABLE == 0)
val report = measure()
val json = report.toString()
output.putString("benchmark", json)
finish(Activity.RESULT_OK, output)
} catch (error: Throwable) {
val trace = error.stackTraceToString()
output.putString("error", trace)
finish(Activity.RESULT_CANCELED, output)
}
}

private fun measure(): JSONObject {
val worker = Executors.newSingleThreadExecutor()
try {
val mainTid = onMain { Process.myTid() }
val readTid = Callable { Process.myTid() }
val workerIdentity = worker.submit(readTid)
val workerTid = workerIdentity.get()
val pid = Process.myPid()
check(mainTid == pid && workerTid != mainTid)
val probe = onMain { ThreadBenchmark("owner-check") }
val rejectEnd = Callable {
val attempt = runCatching { probe.end() }
val error = attempt.exceptionOrNull()
check(error is IllegalStateException)
}
val wrongThread = worker.submit(rejectEnd)
wrongThread.get()
onMain { probe.end() }
onMain(rejectEnd)

val hermes = onMain { measureHermes() }
val hermesTid = hermes.getInt("threadId")
check(hermesTid == mainTid)

val hashOnWorker = Callable { workload("worker", workerBlocks) }
val start = SystemClock.elapsedRealtimeNanos()
val future = worker.submit(hashOnWorker)
val main = onMain { workload("main", 32) }
val background = future.get()
val elapsedNs = SystemClock.elapsedRealtimeNanos() - start
val measuredMainTid = main.getInt("threadId")
val measuredWorkerTid = background.getInt("threadId")
check(measuredMainTid == mainTid && measuredWorkerTid == workerTid)
return JSONObject()
.put("actionElapsedMs", elapsedNs / 1e6)
.put("hermes", hermes)
.put("main", main)
.put("worker", background)
} finally {
worker.shutdown()
}
}

private fun measureHermes(): JSONObject {
val fixture = targetContext.cacheDir.resolve("perfkit-benchmark.hbc")
context.assets.open("benchmark.hbc").use { input ->
fixture.outputStream().use { output -> input.copyTo(output) }
}
val runtime = JSRuntime(targetContext)
return runtime.use {
val result = it.evaluateFile(fixture.absolutePath)
JSONObject(result)
}
}

private fun digestBlocks(digest: MessageDigest, blocks: Int): ByteArray {
repeat(blocks) { digest.update(block) }
return digest.digest()
}

private fun workload(name: String, blocks: Int): JSONObject {
val digest = MessageDigest.getInstance("SHA-256")
digestBlocks(digest, 1)
val window = ThreadBenchmark(name)
val hash = digestBlocks(digest, blocks)
val result = window.end()
val checksum = Base64.encodeToString(hash, Base64.NO_WRAP)
return JSONObject()
.put("name", result.name)
.put("blocks", blocks)
.put("checksum", checksum)
.put("threadId", result.threadId)
.put("elapsedMs", result.elapsedMs)
.put("threadCpuMs", result.threadCpuMs)
.put("countersAvailable", result.countersAvailable)
.put("instructions", result.instructions)
.put("cycles", result.cycles)
.put("timeEnabledNs", result.timeEnabledNs)
.put("timeRunningNs", result.timeRunningNs)
.put("counterErrno", result.counterErrno)
}

private fun <T> onMain(block: Callable<T>): T {
val task = FutureTask(block)
runOnMainSync(task)
return task.get()
}
}
Loading
Loading