Port the Developer app's resource monitor to iOS
This commit is contained in:
1 parent
c5f80a0b00
commit
f47d82b871
13 files changed
+344
-74
No files matched your search
@@ -13,7 +13,7 @@ class FaceclawResourceUsage private constructor() {
|
||||
companion object {
|
||||
/**
|
||||
* Returns elapsedMs, processCpuMs, rssKb, nativeHeapKb, javaHeapKb,
|
||||
* javaHeapCommittedKb, and threadCount. Reading /proc/self/status avoids
|
||||
* javaHeapCommittedKb, threadCount, and peakRssKb. Reading /proc/self/status avoids
|
||||
* the considerably heavier full Debug.MemoryInfo/PSS collection once per
|
||||
* second while still reporting the RSS that Android records at exit.
|
||||
*/
|
||||
@@ -30,30 +30,34 @@ class FaceclawResourceUsage private constructor() {
|
||||
javaUsedBytes / 1024L,
|
||||
runtime.totalMemory() / 1024L,
|
||||
status[1],
|
||||
status[2],
|
||||
)
|
||||
}
|
||||
|
||||
/** Returns {VmRSS in KiB, thread count}; unavailable values are zero. */
|
||||
/** Returns {VmRSS in KiB, thread count, VmHWM in KiB}; unavailable values are zero. */
|
||||
private fun readProcessStatus(): LongArray {
|
||||
var rssKb = 0L
|
||||
var threadCount = 0L
|
||||
var peakRssKb = 0L
|
||||
try {
|
||||
BufferedReader(FileReader("/proc/self/status")).use { reader ->
|
||||
var line: String?
|
||||
while (reader.readLine().also { line = it } != null) {
|
||||
val current = line!!
|
||||
if (current.startsWith("VmRSS:")) {
|
||||
if (current.startsWith("VmHWM:")) {
|
||||
peakRssKb = firstNumber(current)
|
||||
} else if (current.startsWith("VmRSS:")) {
|
||||
rssKb = firstNumber(current)
|
||||
} else if (current.startsWith("Threads:")) {
|
||||
threadCount = firstNumber(current)
|
||||
}
|
||||
if (rssKb > 0 && threadCount > 0) break
|
||||
if (rssKb > 0 && threadCount > 0 && peakRssKb > 0) break
|
||||
}
|
||||
}
|
||||
} catch (ignored: IOException) {
|
||||
// The graph remains useful with the runtime heap counters alone.
|
||||
}
|
||||
return longArrayOf(rssKb, threadCount)
|
||||
return longArrayOf(rssKb, threadCount, peakRssKb)
|
||||
}
|
||||
|
||||
private fun firstNumber(line: String): Long {
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
/** Lightweight process counters for the on-glasses resource-usage monitor. */
|
||||
@interface FaceclawResourceUsage : NSObject
|
||||
/**
|
||||
* One sample as a JSON object: atMs (monotonic clock, counting sleep), cpuMs
|
||||
* (user+system time of every thread, alive or exited), footprintKb (the
|
||||
* phys_footprint that jetsam limits and Xcode's memory gauge shows),
|
||||
* footprintPeakKb (lifetime peak), residentKb, mallocKb (bytes in use across
|
||||
* malloc zones), availableKb (headroom before the jetsam limit; 0 when there
|
||||
* is none, as on the simulator), threads, thermalState
|
||||
* (NSProcessInfoThermalState) and lowPower. Fields whose query fails are
|
||||
* omitted.
|
||||
*/
|
||||
+ (NSString *)sample;
|
||||
@end
|
||||
@@ -0,0 +1,60 @@
|
||||
#import "FaceclawResourceUsage.h"
|
||||
#import <TargetConditionals.h>
|
||||
#import <mach/mach.h>
|
||||
#import <malloc/malloc.h>
|
||||
#import <sys/resource.h>
|
||||
#import <time.h>
|
||||
#if TARGET_OS_IPHONE
|
||||
#import <os/proc.h>
|
||||
#endif
|
||||
|
||||
static NSNumber *kib(uint64_t bytes) { return @(bytes / 1024); }
|
||||
|
||||
@implementation FaceclawResourceUsage
|
||||
+ (NSString *)sample {
|
||||
NSMutableDictionary *out = [NSMutableDictionary new];
|
||||
out[@"atMs"] = @(clock_gettime_nsec_np(CLOCK_MONOTONIC) / 1000000ULL);
|
||||
|
||||
struct rusage usage;
|
||||
if (getrusage(RUSAGE_SELF, &usage) == 0) {
|
||||
double seconds = (double)usage.ru_utime.tv_sec + (double)usage.ru_stime.tv_sec;
|
||||
double micros = (double)usage.ru_utime.tv_usec + (double)usage.ru_stime.tv_usec;
|
||||
out[@"cpuMs"] = @(seconds * 1000.0 + micros / 1000.0);
|
||||
}
|
||||
|
||||
// The kernel fills as much of the struct as it knows and shrinks count to
|
||||
// match, so later-revision fields are read only when count covers them.
|
||||
task_vm_info_data_t vm;
|
||||
mach_msg_type_number_t count = TASK_VM_INFO_COUNT;
|
||||
if (task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&vm, &count) == KERN_SUCCESS) {
|
||||
out[@"residentKb"] = kib(vm.resident_size);
|
||||
if (count >= TASK_VM_INFO_REV1_COUNT) out[@"footprintKb"] = kib(vm.phys_footprint);
|
||||
if (count >= TASK_VM_INFO_REV3_COUNT && vm.ledger_phys_footprint_peak > 0) {
|
||||
out[@"footprintPeakKb"] = kib((uint64_t)vm.ledger_phys_footprint_peak);
|
||||
}
|
||||
}
|
||||
|
||||
malloc_statistics_t heap = {0};
|
||||
malloc_zone_statistics(NULL, &heap);
|
||||
out[@"mallocKb"] = kib(heap.size_in_use);
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
out[@"availableKb"] = kib(os_proc_available_memory());
|
||||
#endif
|
||||
|
||||
thread_act_array_t threads = NULL;
|
||||
mach_msg_type_number_t threadCount = 0;
|
||||
if (task_threads(mach_task_self(), &threads, &threadCount) == KERN_SUCCESS) {
|
||||
for (mach_msg_type_number_t i = 0; i < threadCount; i++) mach_port_deallocate(mach_task_self(), threads[i]);
|
||||
vm_deallocate(mach_task_self(), (vm_address_t)threads, threadCount * sizeof(thread_act_t));
|
||||
out[@"threads"] = @(threadCount);
|
||||
}
|
||||
|
||||
NSProcessInfo *process = NSProcessInfo.processInfo;
|
||||
out[@"thermalState"] = @(process.thermalState);
|
||||
out[@"lowPower"] = @(process.lowPowerModeEnabled);
|
||||
|
||||
NSData *json = [NSJSONSerialization dataWithJSONObject:out options:0 error:nil];
|
||||
return json ? [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding] : @"{}";
|
||||
}
|
||||
@end
|
||||
@@ -13,5 +13,6 @@ module FaceclawGraphics {
|
||||
header "FaceclawQrScanner.h"
|
||||
header "FaceclawLoopbackRedirect.h"
|
||||
header "FaceclawWebSignIn.h"
|
||||
header "FaceclawResourceUsage.h"
|
||||
export *
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
* Ensure connection is re-set to 2M on reconnect
|
||||
* Add support for embedded icons and custom layouts in Android notifications
|
||||
* iOS: Notifications are selectable via the task switcher
|
||||
* Port the Developer app's resource-usage monitor and various test pages to iOS
|
||||
|
||||
## 0.8.5 - 2026-10-25
|
||||
|
||||
|
||||
@@ -114,8 +114,6 @@ export function createDeveloperAppWindow(appContext: AppContext, options: InProc
|
||||
},
|
||||
{
|
||||
label: "Show resource usage",
|
||||
disabled: global.isIOS,
|
||||
description: global.isIOS ? "Not available on iOS yet." : undefined,
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.push(new ResourceUsageLayer(DEVELOPER_WINDOW_ID, ctx.actions.requestRender));
|
||||
},
|
||||
|
||||
@@ -4,25 +4,23 @@ import { clamp } from "../../util/numeric-util";
|
||||
import { GESTURE_DOUBLE_CLICK, type InputEvent } from "../../ui/gestures";
|
||||
import { Layer, type LayerContext } from "../../ui/layers";
|
||||
import { shell } from "../../ui/shell/shell";
|
||||
|
||||
declare const com: any;
|
||||
import {
|
||||
MEMORY_SERIES,
|
||||
formatMb,
|
||||
sampleResourceUsage,
|
||||
type ResourceSample,
|
||||
} from "../../native/resource-usage";
|
||||
|
||||
const SAMPLE_INTERVAL_MS = 1_000;
|
||||
const HISTORY_MS = 60_000;
|
||||
const MAX_SAMPLES = Math.ceil(HISTORY_MS / SAMPLE_INTERVAL_MS) + 2;
|
||||
/** Line brightness per memory series, headline first. */
|
||||
const MEMORY_SHADES = [240, 155, 80];
|
||||
|
||||
type ResourceSample = {
|
||||
atMs: number;
|
||||
rssMb: number;
|
||||
nativeMb: number;
|
||||
javaMb: number;
|
||||
javaCommittedMb: number;
|
||||
cpuPercent: number;
|
||||
threads: number;
|
||||
};
|
||||
type ChartSample = ResourceSample & { cpuPercent: number };
|
||||
|
||||
type Series = {
|
||||
value: (sample: ResourceSample) => number;
|
||||
value: (sample: ChartSample) => number;
|
||||
shade: number;
|
||||
};
|
||||
|
||||
@@ -30,9 +28,10 @@ type Series = {
|
||||
* One-minute process monitor. Sampling deliberately continues while another
|
||||
* window is foreground so switching back reveals the resource cost of that
|
||||
* workload. Repaints remain visibility-gated to avoid creating hidden frames.
|
||||
* Which memory figures are charted is up to the platform (MEMORY_SERIES).
|
||||
*/
|
||||
export class ResourceUsageLayer implements Layer {
|
||||
private readonly samples: ResourceSample[] = [];
|
||||
private readonly samples: ChartSample[] = [];
|
||||
private timer: ReturnType<typeof setInterval> | null = null;
|
||||
private removed = false;
|
||||
private previousElapsedMs = 0;
|
||||
@@ -68,34 +67,34 @@ export class ResourceUsageLayer implements Layer {
|
||||
return image;
|
||||
}
|
||||
|
||||
const cpuText = `CPU ${formatPercent(latest.cpuPercent)} ${latest.threads} threads`;
|
||||
image.drawText(font, width - 16 - font.measureText(cpuText), 5, cpuText, 200);
|
||||
image.drawText(font, 16, 21, this.sampleError || latest.status, this.sampleError ? 170 : 140);
|
||||
|
||||
const memorySeries = MEMORY_SERIES.map((label, index) => ({
|
||||
label,
|
||||
shade: MEMORY_SHADES[index] ?? 80,
|
||||
value: (sample: ChartSample) => sample.memoryMb[index] ?? 0,
|
||||
}));
|
||||
const memoryPeak = Math.max(...this.samples.flatMap((sample) => sample.memoryMb), 64);
|
||||
const memoryScale = roundUp(memoryPeak * 1.08, 64);
|
||||
const legendLeft = drawLegend(
|
||||
image,
|
||||
font,
|
||||
width,
|
||||
48,
|
||||
memorySeries.map((series) => [`${series.label} ${formatMb(series.value(latest))}`, series.shade] as const),
|
||||
);
|
||||
const scaleLabel = `Memory 0–${formatMb(memoryScale)}`;
|
||||
const shortScaleLabel = `0–${formatMb(memoryScale)}`;
|
||||
image.drawText(
|
||||
font,
|
||||
16,
|
||||
21,
|
||||
`RSS ${formatMb(latest.rssMb)} native ${formatMb(latest.nativeMb)} Java ${formatMb(latest.javaMb)}/${formatMb(latest.javaCommittedMb)}`,
|
||||
190,
|
||||
48,
|
||||
16 + font.measureText(scaleLabel) + 8 <= legendLeft ? scaleLabel : shortScaleLabel,
|
||||
140,
|
||||
);
|
||||
image.drawText(
|
||||
font,
|
||||
width - 16 - font.measureText(`CPU ${formatPercent(latest.cpuPercent)} threads ${latest.threads}`),
|
||||
47 - font.lineHeight,
|
||||
`CPU ${formatPercent(latest.cpuPercent)} threads ${latest.threads}`,
|
||||
155,
|
||||
);
|
||||
|
||||
const memoryPeak = Math.max(...this.samples.map((sample) => sample.rssMb), 64);
|
||||
const memoryScale = roundUp(memoryPeak * 1.08, 64);
|
||||
image.drawText(font, 16, 48, `Memory 0–${formatMb(memoryScale)}`, 140);
|
||||
drawLegend(image, font, width, 48, [
|
||||
["RSS", 240],
|
||||
["native", 155],
|
||||
["Java", 80],
|
||||
]);
|
||||
drawChart(image, this.samples, latest.atMs, { x: 16, y: 64, width: width - 32, height: 70 }, memoryScale, [
|
||||
{ value: (sample) => sample.rssMb, shade: 240 },
|
||||
{ value: (sample) => sample.nativeMb, shade: 155 },
|
||||
{ value: (sample) => sample.javaMb, shade: 80 },
|
||||
]);
|
||||
drawChart(image, this.samples, latest.atMs, { x: 16, y: 64, width: width - 32, height: 70 }, memoryScale, memorySeries);
|
||||
|
||||
const cpuPeak = Math.max(...this.samples.map((sample) => sample.cpuPercent), 100);
|
||||
const cpuScale = roundUp(cpuPeak * 1.08, 25);
|
||||
@@ -119,26 +118,16 @@ export class ResourceUsageLayer implements Layer {
|
||||
private takeSample(): void {
|
||||
if (this.removed) return;
|
||||
try {
|
||||
const raw = com.faceclaw.app.FaceclawResourceUsage.sample();
|
||||
const atMs = Number(raw[0]);
|
||||
const cpuMs = Number(raw[1]);
|
||||
const elapsedDelta = atMs - this.previousElapsedMs;
|
||||
const cpuDelta = cpuMs - this.previousCpuMs;
|
||||
const sample = sampleResourceUsage();
|
||||
const elapsedDelta = sample.atMs - this.previousElapsedMs;
|
||||
const cpuDelta = sample.cpuMs - this.previousCpuMs;
|
||||
const cpuPercent = this.previousElapsedMs > 0 && elapsedDelta > 0
|
||||
? Math.max(0, cpuDelta / elapsedDelta * 100)
|
||||
: 0;
|
||||
this.previousElapsedMs = atMs;
|
||||
this.previousCpuMs = cpuMs;
|
||||
this.samples.push({
|
||||
atMs,
|
||||
cpuPercent,
|
||||
rssMb: kbToMb(Number(raw[2])),
|
||||
nativeMb: kbToMb(Number(raw[3])),
|
||||
javaMb: kbToMb(Number(raw[4])),
|
||||
javaCommittedMb: kbToMb(Number(raw[5])),
|
||||
threads: Number(raw[6]),
|
||||
});
|
||||
const cutoff = atMs - HISTORY_MS;
|
||||
this.previousElapsedMs = sample.atMs;
|
||||
this.previousCpuMs = sample.cpuMs;
|
||||
this.samples.push({ ...sample, cpuPercent });
|
||||
const cutoff = sample.atMs - HISTORY_MS;
|
||||
while (this.samples.length > 1 && this.samples[0]!.atMs < cutoff) this.samples.shift();
|
||||
while (this.samples.length > MAX_SAMPLES) this.samples.shift();
|
||||
this.sampleError = "";
|
||||
@@ -153,7 +142,7 @@ export class ResourceUsageLayer implements Layer {
|
||||
|
||||
function drawChart(
|
||||
image: GrayImage,
|
||||
samples: readonly ResourceSample[],
|
||||
samples: readonly ChartSample[],
|
||||
nowMs: number,
|
||||
bounds: { x: number; y: number; width: number; height: number },
|
||||
scale: number,
|
||||
@@ -163,7 +152,8 @@ function drawChart(
|
||||
const midY = bounds.y + Math.round((bounds.height - 1) / 2);
|
||||
image.drawLine(bounds.x + 1, midY, bounds.x + bounds.width - 2, midY, 24);
|
||||
const startMs = nowMs - HISTORY_MS;
|
||||
for (const item of series) {
|
||||
// Back to front, so the headline series is drawn on top where lines cross.
|
||||
for (const item of [...series].reverse()) {
|
||||
let previous: { x: number; y: number } | null = null;
|
||||
for (const sample of samples) {
|
||||
if (sample.atMs < startMs) continue;
|
||||
@@ -177,36 +167,30 @@ function drawChart(
|
||||
}
|
||||
}
|
||||
|
||||
/** Right-aligned legend of line swatches and labels; returns its left edge. */
|
||||
function drawLegend(
|
||||
image: GrayImage,
|
||||
font: ReturnType<typeof getDefaultSmallFont>,
|
||||
width: number,
|
||||
y: number,
|
||||
entries: ReadonlyArray<readonly [string, number]>,
|
||||
): void {
|
||||
): number {
|
||||
const totalWidth = entries.reduce((sum, [label]) => sum + font.measureText(label) + 14, 0);
|
||||
let x = width - 16 - totalWidth;
|
||||
const left = width - 16 - totalWidth;
|
||||
let x = left;
|
||||
for (const [label, shade] of entries) {
|
||||
image.drawLine(x, y + 6, x + 8, y + 6, shade);
|
||||
x += 12;
|
||||
image.drawText(font, x, y, label, shade);
|
||||
x += font.measureText(label) + 2;
|
||||
}
|
||||
}
|
||||
|
||||
function kbToMb(kb: number): number {
|
||||
return Math.max(0, kb) / 1024;
|
||||
return left;
|
||||
}
|
||||
|
||||
function roundUp(value: number, step: number): number {
|
||||
return Math.max(step, Math.ceil(value / step) * step);
|
||||
}
|
||||
|
||||
function formatMb(value: number): string {
|
||||
if (value >= 1024) return `${(value / 1024).toFixed(1)}G`;
|
||||
return `${Math.round(value)}M`;
|
||||
}
|
||||
|
||||
function formatPercent(value: number): string {
|
||||
return `${value < 10 ? value.toFixed(1) : Math.round(value)}%`;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/** Platform-neutral process resource sample, shared by resource-usage.ts and resource-usage.ios.ts. */
|
||||
|
||||
export type ResourceSample = {
|
||||
/** Monotonic clock (counting deep sleep), ms. */
|
||||
atMs: number;
|
||||
/** Cumulative CPU time of every thread in the process, ms. */
|
||||
cpuMs: number;
|
||||
threads: number;
|
||||
/** One value per entry of the platform's MEMORY_SERIES, MiB. */
|
||||
memoryMb: number[];
|
||||
/** Platform-specific details for the latest sample (peaks, limits, thermal state). */
|
||||
status: string;
|
||||
};
|
||||
|
||||
export function kbToMb(kb: number): number {
|
||||
return Number.isFinite(kb) ? Math.max(0, kb) / 1024 : 0;
|
||||
}
|
||||
|
||||
export function formatMb(value: number): string {
|
||||
if (value >= 1024) return `${(value / 1024).toFixed(1)}G`;
|
||||
return `${Math.round(value)}M`;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { formatMb, kbToMb, type ResourceSample } from "./resource-usage-types";
|
||||
|
||||
export * from "./resource-usage-types";
|
||||
|
||||
declare const FaceclawResourceUsage: any;
|
||||
|
||||
/**
|
||||
* Memory series charted by the resource monitor, headline first: the physical
|
||||
* footprint (what jetsam enforces its limit against, and what Xcode's memory
|
||||
* gauge shows), resident memory, and bytes in use across the malloc zones.
|
||||
*/
|
||||
export const MEMORY_SERIES: readonly string[] = ["footprint", "resident", "malloc"];
|
||||
|
||||
const THERMAL_STATES = ["nominal", "fair", "serious", "critical"];
|
||||
|
||||
export function sampleResourceUsage(): ResourceSample {
|
||||
const raw = JSON.parse(String(FaceclawResourceUsage.sample())) as Record<string, number | boolean | undefined>;
|
||||
const kb = (key: string) => kbToMb(Number(raw[key] ?? 0));
|
||||
const footprintMb = kb("footprintKb");
|
||||
const peakMb = kb("footprintPeakKb");
|
||||
const availableMb = kb("availableKb");
|
||||
const thermal = THERMAL_STATES[Number(raw.thermalState)];
|
||||
return {
|
||||
atMs: Number(raw.atMs),
|
||||
cpuMs: Number(raw.cpuMs ?? 0),
|
||||
threads: Number(raw.threads ?? 0),
|
||||
memoryMb: [footprintMb, kb("residentKb"), kb("mallocKb")],
|
||||
status: [
|
||||
// Footprint plus the remaining headroom is the jetsam limit. No headroom
|
||||
// means no limit applies (the simulator) or it was just exceeded.
|
||||
availableMb > 0 ? `limit ${formatMb(footprintMb + availableMb)}` : "",
|
||||
peakMb > 0 ? `peak ${formatMb(peakMb)}` : "",
|
||||
thermal ? `thermal ${thermal}` : "",
|
||||
raw.lowPower === true ? "Low Power Mode" : "",
|
||||
].filter(Boolean).join(" · "),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { formatMb, kbToMb, type ResourceSample } from "./resource-usage-types";
|
||||
|
||||
export * from "./resource-usage-types";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
/**
|
||||
* Memory series charted by the resource monitor, headline first: RSS from
|
||||
* /proc/self/status (what Android records at exit), the native malloc heap,
|
||||
* and the used Java heap.
|
||||
*/
|
||||
export const MEMORY_SERIES: readonly string[] = ["RSS", "native", "Java"];
|
||||
|
||||
export function sampleResourceUsage(): ResourceSample {
|
||||
const raw = com.faceclaw.app.FaceclawResourceUsage.sample();
|
||||
const peakRssMb = kbToMb(Number(raw[7]));
|
||||
const javaCommittedMb = kbToMb(Number(raw[5]));
|
||||
return {
|
||||
atMs: Number(raw[0]),
|
||||
cpuMs: Number(raw[1]),
|
||||
memoryMb: [kbToMb(Number(raw[2])), kbToMb(Number(raw[3])), kbToMb(Number(raw[4]))],
|
||||
threads: Number(raw[6]),
|
||||
status: [
|
||||
peakRssMb > 0 ? `peak RSS ${formatMb(peakRssMb)}` : "",
|
||||
`Java heap ${formatMb(javaCommittedMb)} committed`,
|
||||
].filter(Boolean).join(" · "),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Exercise the iOS resource sampler's mach/malloc/rusage queries natively (on macOS).
|
||||
const { execFileSync } = require('node:child_process');
|
||||
const { mkdtempSync, rmSync } = require('node:fs');
|
||||
const { tmpdir } = require('node:os');
|
||||
const { join, resolve } = require('node:path');
|
||||
const root = resolve(__dirname, '..'), dir = mkdtempSync(join(tmpdir(), 'faceclaw-resource-usage-'));
|
||||
try {
|
||||
execFileSync('xcrun', ['clang', '-fobjc-arc', '-framework', 'Foundation', '-I', 'App_Resources/iOS/src',
|
||||
'tests/native/ios-resource-usage-test.m', 'App_Resources/iOS/src/FaceclawResourceUsage.m',
|
||||
'-o', join(dir, 'resource-usage-test')], { cwd: root, stdio: 'inherit' });
|
||||
execFileSync(join(dir, 'resource-usage-test'), [], { stdio: 'inherit' });
|
||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
@@ -0,0 +1,59 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <stdlib.h>
|
||||
#import <string.h>
|
||||
#import "FaceclawResourceUsage.h"
|
||||
|
||||
static NSDictionary *sample(void) {
|
||||
NSData *json = [[FaceclawResourceUsage sample] dataUsingEncoding:NSUTF8StringEncoding];
|
||||
return [NSJSONSerialization JSONObjectWithData:json options:0 error:nil];
|
||||
}
|
||||
|
||||
#define CHECK(cond, ...) do { if (!(cond)) { NSLog(@"FAIL " __VA_ARGS__); return 1; } } while (0)
|
||||
|
||||
int main(void) {
|
||||
@autoreleasepool {
|
||||
NSDictionary *before = sample();
|
||||
CHECK([before isKindOfClass:NSDictionary.class], @"sample is not a JSON object");
|
||||
for (NSString *key in @[@"atMs", @"cpuMs", @"footprintKb", @"footprintPeakKb", @"residentKb", @"mallocKb",
|
||||
@"threads", @"thermalState", @"lowPower"]) {
|
||||
CHECK([before[key] isKindOfClass:NSNumber.class], @"missing %@ in %@", key, before);
|
||||
}
|
||||
CHECK(before[@"availableKb"] == nil, @"os_proc_available_memory is iOS-only: %@", before);
|
||||
CHECK([before[@"footprintKb"] longLongValue] > 0 && [before[@"residentKb"] longLongValue] > 0, @"memory %@", before);
|
||||
CHECK([before[@"footprintPeakKb"] longLongValue] >= [before[@"footprintKb"] longLongValue], @"peak %@", before);
|
||||
CHECK([before[@"threads"] intValue] >= 1, @"threads %@", before);
|
||||
|
||||
// Two busy threads alive at sampling time, ~150 ms of work between them;
|
||||
// 64 MiB of touched malloc memory.
|
||||
NSCondition *gate = [NSCondition new];
|
||||
__block BOOL release = NO;
|
||||
__block volatile double sink = 0;
|
||||
for (int t = 0; t < 2; t++) {
|
||||
[NSThread detachNewThreadWithBlock:^{
|
||||
NSDate *until = [NSDate dateWithTimeIntervalSinceNow:0.075];
|
||||
while (until.timeIntervalSinceNow > 0) for (int i = 0; i < 10000; i++) sink += i * 0.5;
|
||||
[gate lock]; while (!release) [gate wait]; [gate unlock];
|
||||
}];
|
||||
}
|
||||
size_t bytes = 64u << 20;
|
||||
char *block = malloc(bytes);
|
||||
memset(block, 1, bytes);
|
||||
[NSThread sleepForTimeInterval:0.2];
|
||||
|
||||
NSDictionary *after = sample();
|
||||
long long elapsed = [after[@"atMs"] longLongValue] - [before[@"atMs"] longLongValue];
|
||||
double cpu = [after[@"cpuMs"] doubleValue] - [before[@"cpuMs"] doubleValue];
|
||||
CHECK(elapsed >= 190 && elapsed < 5000, @"monotonic clock advanced %lld ms over a 200 ms sleep", elapsed);
|
||||
CHECK(cpu >= 100, @"CPU advanced only %.1f ms over ~150 ms of busy work", cpu);
|
||||
CHECK([after[@"threads"] intValue] >= [before[@"threads"] intValue] + 2, @"threads %@ -> %@", before[@"threads"], after[@"threads"]);
|
||||
CHECK([after[@"mallocKb"] longLongValue] - [before[@"mallocKb"] longLongValue] >= 60 * 1024,
|
||||
@"malloc %@ -> %@ after 64 MiB", before[@"mallocKb"], after[@"mallocKb"]);
|
||||
CHECK([after[@"footprintKb"] longLongValue] - [before[@"footprintKb"] longLongValue] >= 60 * 1024,
|
||||
@"footprint %@ -> %@ after touching 64 MiB", before[@"footprintKb"], after[@"footprintKb"]);
|
||||
[gate lock]; release = YES; [gate broadcast]; [gate unlock];
|
||||
free(block);
|
||||
printf("PASS: resource sample reports footprint %lld KiB, malloc %lld KiB, %d threads, %.0f ms CPU over %lld ms\n",
|
||||
[after[@"footprintKb"] longLongValue], [after[@"mallocKb"] longLongValue], [after[@"threads"] intValue], cpu, elapsed);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { loader } = require('./helpers/load-typescript.cjs');
|
||||
|
||||
// The resource monitor's platform samplers, over stand-ins for the iOS
|
||||
// FaceclawResourceUsage JSON and the Android FaceclawResourceUsage LongArray.
|
||||
function ios(raw) {
|
||||
const load = loader({ FaceclawResourceUsage: { sample: () => JSON.stringify(raw) } });
|
||||
return load('app/native/resource-usage.ios.ts');
|
||||
}
|
||||
|
||||
function android(raw) {
|
||||
const load = loader({ com: { faceclaw: { app: { FaceclawResourceUsage: { sample: () => raw } } } } });
|
||||
return load('app/native/resource-usage.ts');
|
||||
}
|
||||
|
||||
test('iOS charts footprint, resident and malloc, and reports the jetsam limit, peak and thermal state', () => {
|
||||
const usage = ios({
|
||||
atMs: 5000, cpuMs: 1234.5, footprintKb: 200 * 1024, footprintPeakKb: 300 * 1024, residentKb: 150 * 1024,
|
||||
mallocKb: 64 * 1024, availableKb: 2848 * 1024, threads: 23, thermalState: 2, lowPower: true,
|
||||
});
|
||||
assert.deepEqual(Array.from(usage.MEMORY_SERIES), ['footprint', 'resident', 'malloc']);
|
||||
const sample = usage.sampleResourceUsage();
|
||||
assert.equal(sample.atMs, 5000);
|
||||
assert.equal(sample.cpuMs, 1234.5);
|
||||
assert.equal(sample.threads, 23);
|
||||
assert.deepEqual(Array.from(sample.memoryMb), [200, 150, 64]);
|
||||
assert.equal(sample.status, 'limit 3.0G · peak 300M · thermal serious · Low Power Mode');
|
||||
});
|
||||
|
||||
test('iOS omits the limit without jetsam headroom, and fields the native query could not fill', () => {
|
||||
const sample = ios({ atMs: 1, footprintKb: 1024, thermalState: 0, lowPower: false }).sampleResourceUsage();
|
||||
assert.equal(sample.cpuMs, 0);
|
||||
assert.equal(sample.threads, 0);
|
||||
assert.deepEqual(Array.from(sample.memoryMb), [1, 0, 0]);
|
||||
assert.equal(sample.status, 'thermal nominal');
|
||||
});
|
||||
|
||||
test('Android charts RSS, native and Java heap, and reports peak RSS and committed Java heap', () => {
|
||||
const usage = android([9000, 4321, 400 * 1024, 48 * 1024, 12 * 1024, 24 * 1024, 87, 512 * 1024]);
|
||||
assert.deepEqual(Array.from(usage.MEMORY_SERIES), ['RSS', 'native', 'Java']);
|
||||
const sample = usage.sampleResourceUsage();
|
||||
assert.equal(sample.atMs, 9000);
|
||||
assert.equal(sample.cpuMs, 4321);
|
||||
assert.equal(sample.threads, 87);
|
||||
assert.deepEqual(Array.from(sample.memoryMb), [400, 48, 12]);
|
||||
assert.equal(sample.status, 'peak RSS 512M · Java heap 24M committed');
|
||||
});
|
||||
Reference in new issue
Block a user