@rnperf/sdk 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,204 @@
1
- # Temporary Holding Version
1
+ # @rnperf/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ In-app performance probe for React Native. Streams JS-thread metrics to the
4
+ [rnperf](../../README.md) daemon, which analyses them and exposes the results over MCP.
5
+
6
+ ```bash
7
+ npm install @rnperf/sdk
8
+ cd ios && pod install # iOS; Android autolinks on the next build
9
+ ```
10
+
11
+ ```ts
12
+ // index.js, before AppRegistry.registerComponent
13
+ import { startPerfMonitor } from '@rnperf/sdk';
14
+
15
+ startPerfMonitor();
16
+ ```
17
+
18
+ No-op in release builds unless `enableInRelease: true` (see [Release builds](#release-builds)).
19
+ Everything it does is wrapped in try/catch — if the daemon is not running, or an internal React
20
+ API has moved, the app behaves exactly as if the SDK were not installed.
21
+
22
+ ## What it reports
23
+
24
+ - **UI FPS and jank** — real frame cadence from the UI thread, measured in-process on both platforms.
25
+ - **JS FPS** — animation frames the JS thread actually serviced.
26
+ - **JS stalls** — how late a fixed-period timer fires, i.e. the longest synchronous block.
27
+ - **JS heap** — Hermes allocator stats, or `performance.memory` elsewhere.
28
+ - **Component renders** — count, self-time and *wasted* renders (props unchanged from the
29
+ previous commit), read from React's own commit data.
30
+ - **Bridge calls** — legacy bridge traffic, via MessageQueue's spy hook.
31
+ - **Memory** — physical footprint on iOS; Java and native heap on Android.
32
+ - **TTI, screens, marks, measures, crashes.**
33
+
34
+ ## Release builds
35
+
36
+ A dev bundle runs hot enough that its numbers are their own story. To measure the build you ship,
37
+ on a device you are holding:
38
+
39
+ ```ts
40
+ startPerfMonitor({ enableInRelease: true, host: '192.168.1.5' });
41
+ ```
42
+
43
+ `host` is **not optional here.** `'auto'` reads Metro's address out of `SourceCode.scriptURL`, and
44
+ a release bundle loads from `assets://` or `file://` — there is nothing to parse. Pass your Mac's
45
+ LAN address. If you forget, the SDK says so in the device log: this one warning is forced past the
46
+ `__DEV__` guard precisely because a release build would otherwise go quiet with no clue why.
47
+
48
+ | Metric | In a release build |
49
+ |---|---|
50
+ | UI frames, jank, refresh rate | Identical. The native modules are not gated on build type |
51
+ | JS fps, stalls, JS heap, bridge calls | Work — and these are the numbers worth quoting |
52
+ | Memory, screens, TTI, marks, measures, crashes | Work |
53
+ | **Component renders** | **Absent** |
54
+
55
+ Renders go for two independent reasons: React's commit hook,
56
+ `__REACT_DEVTOOLS_GLOBAL_HOOK__`, is not installed in a release bundle, and React ships its
57
+ production renderer, which records no timings to read even if it were. Profile in dev to find
58
+ *which component* is at fault; re-record in release to confirm the fix on the real build.
59
+
60
+ Samples carry `runtime.dev: false`, so a release recording is labelled as one.
61
+
62
+ > This is a release-*configuration* build on your own device — not field monitoring. An App Store
63
+ > build on a stranger's phone cannot reach a daemon on your desk, and there is no hosted collector
64
+ > behind this package.
65
+
66
+ ## UI-thread frames
67
+
68
+ The package ships a small native module, `RNPerfFrameMonitor`, on both platforms:
69
+
70
+ | | Mechanism | Also reports |
71
+ |---|---|---|
72
+ | **iOS** | `CADisplayLink` on the main run loop, in `NSRunLoopCommonModes` | physical footprint |
73
+ | **Android** | `Choreographer` frame callback, reposted each frame | Java heap, native heap |
74
+
75
+ Autolinking finds it. On iOS run `pod install`; on Android just rebuild.
76
+
77
+ **Why it exists.** On iOS this is the only way to get the number at all — a simulator exposes no
78
+ Core Animation frame stats and a physical device needs an Instruments GUI trace. On Android the
79
+ daemon already reads richer per-frame data over `adb`, so the module is for the case `adb`
80
+ cannot reach: a device on Wi-Fi, a tester's phone, or CI where only the app reports back.
81
+ **When both are available the device-side values win**, since `dumpsys` sees the whole render
82
+ pipeline and the app can only see its own main thread.
83
+
84
+ Both implementations work the same way:
85
+
86
+ - **Frames accumulate natively and JavaScript drains them once per interval.** A bridge event per
87
+ frame would itself cause the jank this is measuring.
88
+ - **Jank is judged against the display's real budget** — 8.3ms on ProMotion, 11.1ms on a 90Hz
89
+ panel — read from `UIScreen.maximumFramesPerSecond` and `Display.getRefreshRate()`. The rate is
90
+ reported alongside as `uiRefreshHz`.
91
+ - **A frame counts as dropped when the interval exceeds 1.5x the budget**, so ordinary vsync
92
+ jitter is not reported as jank.
93
+ - **Measurement pauses in the background**, so a backgrounded app does not report a multi-second
94
+ stall that never happened.
95
+ - **The buffer is capped at 600 intervals.** If JavaScript is blocked longer than that it is not
96
+ draining anyway; frames past the cap still count towards FPS so a stalled app does not look idle.
97
+
98
+ Caveats:
99
+
100
+ - **Expo Go cannot load it.** Run `npx expo prebuild` and use a development build; everything else
101
+ in the SDK still works in Expo Go.
102
+ - **iOS and Android `jankPercent` are not comparable to `adb gfxinfo`'s.** Both modules count
103
+ refreshes actually missed; `gfxinfo` counts frames whose total latency exceeded budget. Compare
104
+ `uiFps` across platforms instead.
105
+ - **Android reports Java and native heap, not PSS.** `Debug.getMemoryInfo()` takes well over a
106
+ frame to return and would cause the jank the module exists to measure; the daemon reads PSS over
107
+ `adb` instead.
108
+ - **Reposting a frame callback keeps requesting vsync**, which costs a little power — the same
109
+ approach React Native's own FPS monitor uses, and only while the monitor is running.
110
+
111
+ Turn it off with `startPerfMonitor({ trackUiFrames: false })`.
112
+
113
+ ## Options
114
+
115
+ ```ts
116
+ startPerfMonitor({
117
+ host: 'auto', // 'auto' derives it from the Metro bundle URL
118
+ port: 8139,
119
+ intervalMs: 1000,
120
+ trackRenders: true,
121
+ trackBridge: true,
122
+ trackUiFrames: true, // native frame module; no-op where it is absent
123
+ enableInRelease: false, // outside __DEV__; requires an explicit `host`
124
+ bundleId: 'com.example.app',
125
+ onStatus: (s) => console.log('[rnperf]', s),
126
+ });
127
+ ```
128
+
129
+ ## API
130
+
131
+ | Export | Purpose |
132
+ |---|---|
133
+ | `startPerfMonitor(options?)` | Begin reporting |
134
+ | `stopPerfMonitor()` | Stop and disconnect |
135
+ | `setScreen(name)` | Attribute following metrics to a screen |
136
+ | `createNavigationTracker(getRouteName)` | Drop-in for React Navigation's `onStateChange` |
137
+ | `mark(name)` / `measure(name, startMark?)` | Custom timings |
138
+ | `reportTTI(screen?, durationMs?)` | Time to interactive |
139
+ | `trackInteraction(name, durationMs)` | Custom interaction timing |
140
+ | `isPerfMonitorConnected()` | Connection state, for a debug overlay |
141
+
142
+ ## Troubleshooting
143
+
144
+ **iOS build fails in `fmt` with "call to consteval function ... is not a constant expression".**
145
+ This is a React Native issue, not this package: RN 0.81 pins fmt 11.0.2, whose consteval
146
+ format-string checks Xcode 27's clang rejects. It happens with or without this SDK installed.
147
+ Force fmt's detection to the no-consteval branch from your Podfile:
148
+
149
+ ```ruby
150
+ post_install do |installer|
151
+ react_native_post_install(installer, config[:reactNativePath], :mac_catalyst_enabled => false)
152
+
153
+ fmt_base = File.join(installer.sandbox.root, 'fmt', 'include', 'fmt', 'base.h')
154
+ if File.exist?(fmt_base)
155
+ text = File.read(fmt_base)
156
+ patched = text.gsub('# define FMT_USE_CONSTEVAL 1', '# define FMT_USE_CONSTEVAL 0')
157
+ File.write(fmt_base, patched) if patched != text
158
+ end
159
+ end
160
+ ```
161
+
162
+ **Nothing connects from a physical iPhone.** Two things iOS requires that a simulator does not:
163
+
164
+ 1. **Local network permission.** Reaching a daemon on your Mac's LAN address counts as local
165
+ network access. Add to `ios/<App>/Info.plist`, or iOS denies it silently with no prompt:
166
+
167
+ ```xml
168
+ <key>NSLocalNetworkUsageDescription</key>
169
+ <string>Connects to the rnperf daemon on your development machine to report performance metrics.</string>
170
+ ```
171
+
172
+ The first connection then prompts; tap **Allow**. If you declined once, re-enable it under
173
+ Settings → Privacy & Security → Local Network.
174
+
175
+ 2. **An explicit host.** A device cannot reach `localhost`, and with an embedded bundle there is no
176
+ Metro URL to infer from, so pass your Mac's LAN address:
177
+ `startPerfMonitor({ host: '192.168.1.21' })`. This is always the case in a release build.
178
+
179
+ **The app crashes instantly on iOS 26 or newer**, in
180
+ `__UIApplicationEvaluateRuntimeIssueForNoSceneLifecycleAdoption`. Not this SDK: iOS 26 traps apps
181
+ that never adopt the UIScene lifecycle, and the React Native 0.81 template still creates its window
182
+ in `didFinishLaunchingWithOptions`. Move that into a `UIWindowSceneDelegate` and declare it in
183
+ `UIApplicationSceneManifest`.
184
+
185
+ **`nativeModule=MISSING` on iOS.** Run `cd ios && pod install` and rebuild; autolinking only
186
+ picks the pod up at install time.
187
+
188
+ **`nativeModule=MISSING` on Android.** Check `npx react-native config` reports a non-null
189
+ `dependencies['@rnperf/sdk'].platforms.android`, then rebuild.
190
+
191
+ ## Caveats
192
+
193
+ - Render tracking requires a **development build**: React only populates timing data in its
194
+ profiling build, and a release bundle installs no commit hook to report through. Everything
195
+ else still reports — see [Release builds](#release-builds).
196
+ - Under the new architecture most native calls are synchronous JSI and never cross the
197
+ bridge, so `bridgeCalls` reads zero there — that means "nothing on the bridge", not
198
+ "nothing happening".
199
+ - UI-thread frame data needs the native module and therefore a rebuild (plus `pod install` on
200
+ iOS). Without it the SDK still reports everything JS-side; `uiFps` is simply absent.
201
+ - The Android module requires React Native 0.71 or newer, where the `react-android` Maven
202
+ artifact is published. The JavaScript half works from 0.70.
203
+ - `startPerfMonitor()` must run **after** React is imported, so it can attach to React's
204
+ commit hook.
@@ -0,0 +1,21 @@
1
+ require "json"
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = "RNPerfSDK"
7
+ s.version = package["version"]
8
+ s.summary = package["description"]
9
+ s.license = "MIT"
10
+ s.authors = "rnperf"
11
+ s.homepage = "https://github.com/rnperf/react-native-performance-monitor"
12
+ s.platforms = { :ios => "13.0" }
13
+ s.source = { :path => "." }
14
+ s.source_files = "ios/**/*.{h,m}"
15
+ s.frameworks = "UIKit", "QuartzCore"
16
+
17
+ # React-Core brings in RCTBridgeModule. The module is a classic bridge module,
18
+ # which the new architecture still supports through its interop layer, so one
19
+ # implementation covers both the old and the bridgeless runtime.
20
+ s.dependency "React-Core"
21
+ end
@@ -0,0 +1,46 @@
1
+ apply plugin: 'com.android.library'
2
+
3
+ /**
4
+ * Read a property from the host app's rootProject.ext when it defines one, so
5
+ * this module compiles against the same SDK levels as the app including it,
6
+ * and still builds standalone when it does not.
7
+ */
8
+ def safeExtGet(String prop, fallback) {
9
+ rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
10
+ }
11
+
12
+ android {
13
+ // `namespace` replaced the manifest's package attribute in AGP 7.3 and is
14
+ // required by AGP 8. Guarded so older toolchains do not fail on it.
15
+ if (project.android.hasProperty('namespace')) {
16
+ namespace 'com.rnperf.sdk'
17
+ }
18
+
19
+ compileSdk safeExtGet('compileSdkVersion', 34)
20
+
21
+ defaultConfig {
22
+ minSdk safeExtGet('minSdkVersion', 21)
23
+ targetSdk safeExtGet('targetSdkVersion', 34)
24
+ }
25
+
26
+ compileOptions {
27
+ sourceCompatibility JavaVersion.VERSION_1_8
28
+ targetCompatibility JavaVersion.VERSION_1_8
29
+ }
30
+
31
+ // A profiling helper must never be the reason an app build fails.
32
+ lint {
33
+ abortOnError false
34
+ }
35
+ }
36
+
37
+ repositories {
38
+ google()
39
+ mavenCentral()
40
+ }
41
+
42
+ dependencies {
43
+ // Version is supplied by the host app's React Native Gradle plugin.
44
+ //noinspection GradleDynamicVersion
45
+ implementation 'com.facebook.react:react-android'
46
+ }
@@ -0,0 +1,3 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <!-- The package namespace lives in build.gradle; AGP 8 forbids it here. -->
3
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,345 @@
1
+ package com.rnperf.sdk;
2
+
3
+ import android.app.Activity;
4
+ import android.content.Context;
5
+ import android.os.Build;
6
+ import android.os.Debug;
7
+ import android.view.Choreographer;
8
+ import android.view.Display;
9
+ import android.view.WindowManager;
10
+
11
+ import com.facebook.react.bridge.Arguments;
12
+ import com.facebook.react.bridge.LifecycleEventListener;
13
+ import com.facebook.react.bridge.Promise;
14
+ import com.facebook.react.bridge.ReactApplicationContext;
15
+ import com.facebook.react.bridge.ReactContextBaseJavaModule;
16
+ import com.facebook.react.bridge.ReactMethod;
17
+ import com.facebook.react.bridge.UiThreadUtil;
18
+ import com.facebook.react.bridge.WritableMap;
19
+ import com.facebook.react.module.annotations.ReactModule;
20
+
21
+ import java.util.Arrays;
22
+
23
+ /**
24
+ * Samples the Android UI thread's frame cadence with Choreographer.
25
+ *
26
+ * The daemon already reads richer per-frame data over adb when a cable is
27
+ * attached. This exists for the case adb cannot reach: a physical device on
28
+ * Wi-Fi, a tester's phone, or CI where only the app itself reports back. It is
29
+ * the same measurement the iOS module makes, so the two platforms produce
30
+ * directly comparable numbers.
31
+ *
32
+ * Reposting a frame callback each frame schedules the next vsync, so the loop
33
+ * runs at the display's cadence even when nothing on screen changes — the same
34
+ * approach React Native's own FPS monitor uses.
35
+ */
36
+ @ReactModule(name = RNPerfFrameMonitorModule.NAME)
37
+ public class RNPerfFrameMonitorModule extends ReactContextBaseJavaModule
38
+ implements LifecycleEventListener, Choreographer.FrameCallback {
39
+
40
+ public static final String NAME = "RNPerfFrameMonitor";
41
+
42
+ /**
43
+ * At 120Hz this is five seconds of frames. If JavaScript is blocked for
44
+ * longer it is not draining us either, and an unbounded buffer would grow
45
+ * while the app is already in trouble.
46
+ */
47
+ private static final int MAX_BUFFERED_FRAMES = 600;
48
+
49
+ /**
50
+ * An interval beyond this many refresh periods counts as a dropped frame.
51
+ * Inter-frame deltas straddle the budget at steady state, so an exact
52
+ * comparison would flag ordinary vsync jitter.
53
+ */
54
+ private static final double JANK_FACTOR = 1.5;
55
+
56
+ private static final double NANOS_PER_MS = 1_000_000.0;
57
+ private static final double BYTES_PER_MB = 1024.0 * 1024.0;
58
+
59
+ private final double[] intervalsMs = new double[MAX_BUFFERED_FRAMES];
60
+ private int intervalCount = 0;
61
+ private int overflowedFrames = 0;
62
+ private int droppedFrames = 0;
63
+
64
+ private long lastFrameTimeNanos = 0L;
65
+ private long windowStartNanos = 0L;
66
+ private double refreshHz = 60.0;
67
+
68
+ /** The app asked us to measure. Survives a pause, unlike {@link #running}. */
69
+ private boolean enabled = false;
70
+ /** A frame callback is currently scheduled. */
71
+ private boolean running = false;
72
+ private boolean listening = false;
73
+
74
+ public RNPerfFrameMonitorModule(ReactApplicationContext context) {
75
+ super(context);
76
+ // Deliberately no listener registration here: handing `this` to the context
77
+ // from a constructor publishes a reference to a half-built object. Nothing
78
+ // needs lifecycle events until measurement actually starts.
79
+ }
80
+
81
+ @Override
82
+ public String getName() {
83
+ return NAME;
84
+ }
85
+
86
+ /* ------------------------------------------------------------- exported */
87
+
88
+ @ReactMethod
89
+ public void start() {
90
+ UiThreadUtil.runOnUiThread(new Runnable() {
91
+ @Override
92
+ public void run() {
93
+ enabled = true;
94
+ if (!listening) {
95
+ getReactApplicationContext().addLifecycleEventListener(RNPerfFrameMonitorModule.this);
96
+ listening = true;
97
+ }
98
+ startLoop();
99
+ }
100
+ });
101
+ }
102
+
103
+ @ReactMethod
104
+ public void stop() {
105
+ UiThreadUtil.runOnUiThread(new Runnable() {
106
+ @Override
107
+ public void run() {
108
+ enabled = false;
109
+ stopLoop();
110
+ }
111
+ });
112
+ }
113
+
114
+ /**
115
+ * Returns the window accumulated since the previous call and starts a new
116
+ * one. Resolved from the UI thread so the frame buffers are only ever
117
+ * touched by one thread, with no locking on the hot path.
118
+ */
119
+ @ReactMethod
120
+ public void getMetrics(final Promise promise) {
121
+ UiThreadUtil.runOnUiThread(new Runnable() {
122
+ @Override
123
+ public void run() {
124
+ try {
125
+ promise.resolve(buildMetrics());
126
+ } catch (Exception error) {
127
+ promise.reject("E_RNPERF_METRICS", error);
128
+ }
129
+ }
130
+ });
131
+ }
132
+
133
+ @ReactMethod
134
+ public void isAvailable(Promise promise) {
135
+ promise.resolve(Boolean.TRUE);
136
+ }
137
+
138
+ /* ------------------------------------------------------------ collection */
139
+
140
+ private WritableMap buildMetrics() {
141
+ WritableMap result = Arguments.createMap();
142
+ result.putDouble("refreshHz", refreshHz);
143
+ putMemory(result);
144
+
145
+ if (!running || windowStartNanos == 0L) {
146
+ return result;
147
+ }
148
+
149
+ long now = System.nanoTime();
150
+ double elapsedMs = (now - windowStartNanos) / NANOS_PER_MS;
151
+ int frames = intervalCount + overflowedFrames;
152
+
153
+ // Too short a window makes frames-per-second meaningless.
154
+ if (elapsedMs < 100.0 || frames == 0) {
155
+ return result;
156
+ }
157
+
158
+ result.putInt("framesRendered", frames);
159
+ result.putDouble("uiFps", Math.min(refreshHz, frames / (elapsedMs / 1000.0)));
160
+
161
+ if (intervalCount > 0) {
162
+ double[] sorted = Arrays.copyOf(intervalsMs, intervalCount);
163
+ Arrays.sort(sorted);
164
+ result.putDouble("frameP50Ms", quantile(sorted, 0.50));
165
+ result.putDouble("frameP95Ms", quantile(sorted, 0.95));
166
+ result.putDouble("frameP99Ms", quantile(sorted, 0.99));
167
+ }
168
+
169
+ // Express jank as a share of the frames the display could have shown,
170
+ // rather than of the ones it managed to.
171
+ double expected = (elapsedMs / 1000.0) * refreshHz;
172
+ if (expected >= 1.0) {
173
+ double jank = (droppedFrames / expected) * 100.0;
174
+ result.putDouble("jankPercent", Math.max(0.0, Math.min(100.0, jank)));
175
+ }
176
+
177
+ resetWindow();
178
+ return result;
179
+ }
180
+
181
+ /**
182
+ * Java and native heap only. Proportional set size would be the better
183
+ * number, but {@code Debug.getMemoryInfo} takes well over a frame to return
184
+ * and would cause the jank this module exists to measure. The daemon reads
185
+ * PSS over adb instead, when a cable is attached.
186
+ */
187
+ private void putMemory(WritableMap result) {
188
+ try {
189
+ Runtime runtime = Runtime.getRuntime();
190
+ double javaHeapMB = (runtime.totalMemory() - runtime.freeMemory()) / BYTES_PER_MB;
191
+ result.putDouble("javaHeapMB", javaHeapMB);
192
+ result.putDouble("nativeHeapMB", Debug.getNativeHeapAllocatedSize() / BYTES_PER_MB);
193
+ } catch (Throwable ignored) {
194
+ // Memory is a bonus here; never fail a frame report over it.
195
+ }
196
+ }
197
+
198
+ /* --------------------------------------------------------- frame callback */
199
+
200
+ @Override
201
+ public void doFrame(long frameTimeNanos) {
202
+ if (!running) {
203
+ return;
204
+ }
205
+
206
+ if (lastFrameTimeNanos == 0L) {
207
+ // First callback after start or resume: there is no previous frame to
208
+ // measure against, and the gap would read as an enormous stall.
209
+ lastFrameTimeNanos = frameTimeNanos;
210
+ Choreographer.getInstance().postFrameCallback(this);
211
+ return;
212
+ }
213
+
214
+ double intervalMs = (frameTimeNanos - lastFrameTimeNanos) / NANOS_PER_MS;
215
+ lastFrameTimeNanos = frameTimeNanos;
216
+
217
+ if (intervalMs > 0.0) {
218
+ double budgetMs = 1000.0 / refreshHz;
219
+ if (intervalMs > budgetMs * JANK_FACTOR) {
220
+ // One long interval can swallow several refreshes; count each.
221
+ int missed = (int) Math.round(intervalMs / budgetMs) - 1;
222
+ droppedFrames += Math.max(1, missed);
223
+ }
224
+ if (intervalCount < MAX_BUFFERED_FRAMES) {
225
+ intervalsMs[intervalCount++] = intervalMs;
226
+ } else {
227
+ // Still count it towards FPS once the buffer is full, so a long JS
228
+ // stall does not make the app look idle.
229
+ overflowedFrames++;
230
+ }
231
+ }
232
+
233
+ Choreographer.getInstance().postFrameCallback(this);
234
+ }
235
+
236
+ /* -------------------------------------------------------------- lifecycle */
237
+
238
+ @Override
239
+ public void onHostResume() {
240
+ if (enabled) {
241
+ startLoop();
242
+ }
243
+ }
244
+
245
+ @Override
246
+ public void onHostPause() {
247
+ // A backgrounded app receives no frames. Left running, the next window
248
+ // would report zero FPS and a stall of however long it was away.
249
+ stopLoop();
250
+ }
251
+
252
+ @Override
253
+ public void onHostDestroy() {
254
+ enabled = false;
255
+ stopLoop();
256
+ if (listening) {
257
+ getReactApplicationContext().removeLifecycleEventListener(this);
258
+ listening = false;
259
+ }
260
+ }
261
+
262
+ /* ---------------------------------------------------------------- helpers */
263
+
264
+ private void startLoop() {
265
+ if (running) {
266
+ return;
267
+ }
268
+ refreshHz = readRefreshHz();
269
+ lastFrameTimeNanos = 0L;
270
+ resetWindow();
271
+ running = true;
272
+ Choreographer.getInstance().postFrameCallback(this);
273
+ }
274
+
275
+ private void stopLoop() {
276
+ if (!running) {
277
+ return;
278
+ }
279
+ running = false;
280
+ Choreographer.getInstance().removeFrameCallback(this);
281
+ lastFrameTimeNanos = 0L;
282
+ }
283
+
284
+ private void resetWindow() {
285
+ intervalCount = 0;
286
+ overflowedFrames = 0;
287
+ droppedFrames = 0;
288
+ windowStartNanos = System.nanoTime();
289
+ }
290
+
291
+ /**
292
+ * The display's current mode, not its maximum: a 120Hz panel running at 60Hz
293
+ * has a 16.7ms budget, and holding it to 8.3ms would invent jank.
294
+ */
295
+ @SuppressWarnings("deprecation")
296
+ private double readRefreshHz() {
297
+ try {
298
+ Display display = null;
299
+
300
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
301
+ Activity activity = getCurrentActivity();
302
+ if (activity != null) {
303
+ display = activity.getDisplay();
304
+ }
305
+ }
306
+
307
+ if (display == null) {
308
+ Context context = getReactApplicationContext();
309
+ WindowManager windowManager =
310
+ (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
311
+ if (windowManager != null) {
312
+ display = windowManager.getDefaultDisplay();
313
+ }
314
+ }
315
+
316
+ if (display != null) {
317
+ float hz = display.getRefreshRate();
318
+ if (hz > 20.0f) {
319
+ // The platform reports values like 60.000003814697266; two decimals
320
+ // is well beyond what any frame budget needs.
321
+ return Math.round(hz * 100.0) / 100.0;
322
+ }
323
+ }
324
+ } catch (Throwable ignored) {
325
+ // Fall through to the safe default below.
326
+ }
327
+ return 60.0;
328
+ }
329
+
330
+ private static double quantile(double[] sortedAscending, double q) {
331
+ int n = sortedAscending.length;
332
+ if (n == 0) {
333
+ return 0.0;
334
+ }
335
+ if (n == 1) {
336
+ return sortedAscending[0];
337
+ }
338
+ double position = (n - 1) * q;
339
+ int low = (int) Math.floor(position);
340
+ int high = (int) Math.ceil(position);
341
+ double a = sortedAscending[low];
342
+ double b = sortedAscending[high];
343
+ return low == high ? a : a + (b - a) * (position - low);
344
+ }
345
+ }
@@ -0,0 +1,36 @@
1
+ package com.rnperf.sdk;
2
+
3
+ import com.facebook.react.ReactPackage;
4
+ import com.facebook.react.bridge.NativeModule;
5
+ import com.facebook.react.bridge.ReactApplicationContext;
6
+ import com.facebook.react.uimanager.ViewManager;
7
+
8
+ import java.util.ArrayList;
9
+ import java.util.Collections;
10
+ import java.util.List;
11
+
12
+ /**
13
+ * Registers the frame monitor. Found automatically by React Native autolinking.
14
+ *
15
+ * Uses the eager {@code ReactPackage} API rather than {@code BaseReactPackage}:
16
+ * the latter only exists from React Native 0.74, and this package supports 0.70
17
+ * upwards. The eager form is deprecated but still honoured on every version,
18
+ * including the bridgeless runtime, and one module is not worth the lazy path.
19
+ */
20
+ // `rawtypes` is unavoidable: ReactPackage declares a raw List<ViewManager>, so
21
+ // a parameterised override would not match the interface.
22
+ @SuppressWarnings({"deprecation", "rawtypes"})
23
+ public class RNPerfFrameMonitorPackage implements ReactPackage {
24
+
25
+ @Override
26
+ public List<NativeModule> createNativeModules(ReactApplicationContext context) {
27
+ List<NativeModule> modules = new ArrayList<>();
28
+ modules.add(new RNPerfFrameMonitorModule(context));
29
+ return modules;
30
+ }
31
+
32
+ @Override
33
+ public List<ViewManager> createViewManagers(ReactApplicationContext context) {
34
+ return Collections.emptyList();
35
+ }
36
+ }