diff --git a/.github/workflows/ios-performance.yml b/.github/workflows/ios-performance.yml new file mode 100644 index 000000000..7d486c447 --- /dev/null +++ b/.github/workflows/ios-performance.yml @@ -0,0 +1,116 @@ +name: iOS Simulator performance + +on: + workflow_dispatch: + inputs: + baseline: + description: Baseline commit SHA (defaults to the workflow revision) + type: string + candidate: + description: Candidate commit SHA (defaults to the workflow revision) + type: string + pairs: + description: Measured launch pairs + type: choice + options: ['16', '32', '64'] + default: '32' + positive_control: + description: Also measure 6.25% more candidate layout passes with the same pair count (identical revisions only) + type: boolean + default: false + pull_request: + paths: + - 'packages/nitro-ui-layout-yoga/**' + - 'packages/nitro-ui-layout/**' + - 'scripts/performance/ios/**' + - '.github/workflows/ios-performance.yml' + +permissions: + contents: read + +jobs: + compare: + if: github.event_name == 'workflow_dispatch' || vars.ENABLE_IOS_PERFORMANCE == 'true' + runs-on: macos-26-intel + timeout-minutes: 60 + env: + BASE_SHA: ${{ github.event.pull_request.base.sha || inputs.baseline || github.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha || inputs.candidate || github.sha }} + PAIRS: ${{ inputs.pairs || '32' }} + CONTROL: ${{ inputs.positive_control || false }} + steps: + - name: Validate experiment inputs + shell: bash + run: | + [[ "$BASE_SHA" =~ ^[0-9a-f]{40}$ && "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]] + [[ "$PAIRS" =~ ^(16|32|64)$ ]] + if [[ "$CONTROL" == true && "$BASE_SHA" != "$HEAD_SHA" ]]; then + echo "The positive control requires two builds of the same commit." >&2 + exit 1 + fi + + - name: Check out benchmark fixture and driver + uses: actions/checkout@v7 + with: + ref: ${{ github.event.pull_request.base.sha || github.sha }} + path: control + persist-credentials: false + - name: Check out baseline + uses: actions/checkout@v7 + with: + ref: ${{ env.BASE_SHA }} + path: baseline + persist-credentials: false + - name: Check out candidate + uses: actions/checkout@v7 + with: + repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }} + ref: ${{ env.HEAD_SHA }} + path: candidate + persist-credentials: false + + - name: Build both Release simulator apps + run: | + control/scripts/performance/ios/build.sh baseline baseline "$RUNNER_TEMP/Baseline.app" + control/scripts/performance/ios/build.sh candidate candidate "$RUNNER_TEMP/Candidate.app" + + - name: Boot iPhone 17 with iOS 26.5 + id: simulator + run: | + device=$(xcrun simctl create "Nitro UI benchmark" com.apple.CoreSimulator.SimDeviceType.iPhone-17 com.apple.CoreSimulator.SimRuntime.iOS-26-5) + echo "device=$device" >> "$GITHUB_OUTPUT" + xcrun simctl bootstatus "$device" -b + + - name: Compare paired launches + env: + DEVICE: ${{ steps.simulator.outputs.device }} + run: | + mkdir -p "$RUNNER_TEMP/performance" + { sysctl hw.memsize vm.swapusage; vm_stat; df -h "$RUNNER_TEMP"; } > "$RUNNER_TEMP/performance/host-before.txt" + trap '{ sysctl hw.memsize vm.swapusage; vm_stat; df -h "$RUNNER_TEMP"; } > "$RUNNER_TEMP/performance/host-after.txt"' EXIT + compare() { + python3 control/scripts/performance/ios/compare.py \ + --device "$DEVICE" --baseline "$RUNNER_TEMP/Baseline.app" --candidate "$RUNNER_TEMP/Candidate.app" \ + --baseline-revision "$BASE_SHA" --candidate-revision "$HEAD_SHA" "$@" + } + compare --pairs "$PAIRS" --output "$RUNNER_TEMP/performance/comparison" + cat "$RUNNER_TEMP/performance/comparison/summary.md" >> "$GITHUB_STEP_SUMMARY" + if [[ "$CONTROL" == true ]]; then + compare --positive-control --pairs "$PAIRS" --output "$RUNNER_TEMP/performance/positive-control" + cat "$RUNNER_TEMP/performance/positive-control/summary.md" >> "$GITHUB_STEP_SUMMARY" + fi + + - name: Upload measurements + if: always() + uses: actions/upload-artifact@v7 + with: + name: ios-performance-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/performance + retention-days: 30 + if-no-files-found: warn + + - name: Delete simulator + if: always() && steps.simulator.outputs.device != '' + env: + DEVICE: ${{ steps.simulator.outputs.device }} + run: xcrun simctl delete "$DEVICE" diff --git a/scripts/performance/ios/README.md b/scripts/performance/ios/README.md new file mode 100644 index 000000000..f08c76f63 --- /dev/null +++ b/scripts/performance/ios/README.md @@ -0,0 +1,38 @@ +# iOS Simulator performance + +The [iOS Simulator performance workflow](../../../.github/workflows/ios-performance.yml) compares two Nitro UI commits on one standard GitHub-hosted Intel Mac (`macos-26-intel`). Start it manually with two full commit SHAs. Leave both blank to measure two builds of the same revision (A/A). Select the positive control with identical revisions to run a second comparison with eight extra layout passes in the candidate (+6.25% work). + +Set the repository variable `ENABLE_IOS_PERFORMANCE=true` to run a comparison on pull requests touching the Yoga provider, layout interface, or benchmark. A PR uses the fixture and driver from its base revision. Each revision supplies its own production layout library. The workflow has read-only repository access. A successful check means the two apps produced valid measurements. The job summary shows the estimated change and its uncertainty. + +## What one launch measures + +The fixture mounts 32 rows of eight UIKit views. On the main thread it warms up the layout, opens PerfKit's `ThreadBenchmark`, changes all 256 leaf widths, solves with Nitro UI's Yoga provider, and applies the resulting frames. One sample covers 128 of these passes. It verifies the final geometry and the number of frame updates after closing the measurement window. The fixture compiles the released iOS timing implementation from PerfKit v0.2.1 using its pinned commit and SHA-256 digest. + +Both apps are Release builds with different bundle IDs installed on one iPhone 17 simulator running iOS 26.5. The outputs are wall time and main-thread CPU time for the layout work. App launch, tree construction, and verification fall outside the timed section. The simulator executes on the Mac's CPU. Physical-iPhone frame pacing, GPU rendering, JavaScript, and hardware performance counters are outside this fixture's coverage. + +## Reading the comparison + +Each app writes its nonce and process ID with the result, then exits. The driver validates the result and waits for that process to exit before launching the next arm. A failed launch ends the experiment and leaves the completed samples in the artifact. + +The driver discards two warmup pairs, randomizes which arm launches first, then alternates AB and BA. Each two-pair block yields an order-balanced log ratio. The report converts the median block ratio to a percentage change. Positive means the candidate took longer. + +The job finishes the requested 16, 32, or 64 pairs. At each planned checkpoint it computes rank-based intervals with simultaneous 95% coverage across both metrics and all planned checkpoints, assuming independent blocks with a common median. It records when both intervals first fit within five percentage points of their respective estimated changes. That precision target is separate from the size of regression a maintainer considers acceptable. For example, an interval from −2% to +6% still allows a 5% slowdown. + +The Actions artifact contains `session.json` with revisions, launch order, host and simulator details, `raw.jsonl` with each launch, and `results.json` and `summary.md` with the checkpoint estimates. Each calibration and positive control has its own directory. Reported checkpoint time covers measured launches. Build, simulator boot, installation, and warmup also count toward CI latency. + +## Calibration + +Both apps used Nitro UI commit `9c13ee891421`. The table shows the change at 32 pairs with simultaneous 95% intervals. Each positive control added 6.25% more layout passes. + +| Host and experiment | Measured launches | Wall-time change | Main-thread CPU change | +| --- | ---: | ---: | ---: | +| GitHub Intel, identical builds | 4m06s | −1.11% [−20.02%, +15.65%] | −0.54% [−8.85%, +6.78%] | +| GitHub Intel, positive control | 4m38s | +4.63% [−7.62%, +21.48%] | +8.48% [−0.61%, +19.13%] | +| GitHub ARM, identical builds | 1m56s | −7.44% [−15.28%, +11.62%] | −7.46% [−15.07%, +11.45%] | +| GitHub ARM, positive control | 1m37s | +6.23% [−4.21%, +16.05%] | +6.30% [−3.83%, +15.97%] | +| Local M2 Pro, identical builds | 2m39s | −0.63% [−2.74%, +1.82%] | −0.64% [−2.70%, +1.80%] | +| Local M2 Pro, positive control | 2m25s | +6.43% [+5.07%, +8.79%] | +6.43% [+5.11%, +8.84%] | + +The Intel job waited 36m46s and took 24m21s to run both experiments. The ARM job used an iPhone 17 simulator on iOS 27.0, waited 1h43m for a runner and took 11m48s to run. At 32 pairs the hosted intervals still allowed both zero change and a 5% slowdown. The local simulator used iOS 27.0 on an iPhone 18 Pro device model. Both local comparisons reached the five-point precision target by 16 pairs. [Intel run](https://github.com/margelo/nitro-ui/actions/runs/47147452527) · [ARM run](https://github.com/margelo/nitro-ui/actions/runs/47147360586) + +A second completed Intel comparison ran identical builds for 64 pairs in 9m01s of measured launches. Wall time was −1.78% [−15.25%, +4.23%]. Main-thread CPU time was +1.29% [−7.47%, +7.47%]. Wall time ruled out a 5% slowdown in that run. CPU time still allowed one, and neither metric reached a five-point interval radius. One earlier attempt stopped after three complete pairs when CoreSimulator exceeded its 60-second launch timeout. The repeat allowed 180 seconds for the launch command. No failed samples were retried or pooled. [64-pair result](https://github.com/margelo/nitro-ui/actions/runs/47164590706) · [Incomplete attempt](https://github.com/margelo/nitro-ui/actions/runs/47157888129) diff --git a/scripts/performance/ios/build.sh b/scripts/performance/ios/build.sh new file mode 100755 index 000000000..f032af79f --- /dev/null +++ b/scripts/performance/ios/build.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# != 3 || ! $2 =~ ^(baseline|candidate)$ || $3 != *.app ]]; then + echo "Usage: $0 " >&2 + exit 2 +fi + +source_root=$(cd "$1" && pwd) +fixture_dir=$(cd "$(dirname "$0")/fixture" && pwd) +revision=$(git -C "$source_root" rev-parse HEAD) +output=$3 +if [[ -e "$output" ]]; then + echo "Output already exists: $output" >&2 + exit 2 +fi + +git -C "$source_root" submodule update --init -- packages/nitro-ui-layout-yoga/yoga +scratch=$(mktemp -d) +trap 'rm -rf "$scratch"' EXIT + +# Use the public SDK's standalone ThreadBenchmark at v0.2.1. +sdk_revision=d0f91e83bbe1be64efa3fd60a2a2253b553b5ff1 +sdk_path=packages/react-native-sdk/apple/Sources/CallstackPerformanceAnalytics/ThreadBenchmark.swift +sdk_file="$scratch/ThreadBenchmark.swift" +curl --fail --silent --show-error --location --retry 3 \ + "https://raw.githubusercontent.com/callstackincubator/performance-analytics/$sdk_revision/$sdk_path" -o "$sdk_file" +echo "f7c70f02647cc94580be84cc8ae256d21657f635c53453fc5f3e0bd9d0e28ee8 $sdk_file" | shasum -a 256 -c - + +cmake -S "$fixture_dir" -B "$scratch/build" -G Xcode \ + -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT=iphonesimulator \ + -DCMAKE_OSX_ARCHITECTURES="$(uname -m)" -DCMAKE_OSX_DEPLOYMENT_TARGET=16.0 \ + -DNITRO_SOURCE_ROOT="$source_root" -DTHREAD_BENCHMARK_SOURCE="$sdk_file" \ + -DNITRO_REVISION="$revision" -DNITRO_VARIANT="$2" +cmake --build "$scratch/build" --config Release --target NitroPerf -- -quiet CODE_SIGNING_ALLOWED=NO +mkdir -p "$(dirname "$output")" +ditto "$scratch/build/app/NitroPerf.app" "$output" +codesign --force --sign - "$output" diff --git a/scripts/performance/ios/compare.py b/scripts/performance/ios/compare.py new file mode 100644 index 000000000..9017c03f2 --- /dev/null +++ b/scripts/performance/ios/compare.py @@ -0,0 +1,324 @@ +"""Measure two Release apps on one booted iOS simulator in successive AB/BA blocks.""" + +import argparse +import errno +from datetime import datetime, timezone +import json +import math +import os +from pathlib import Path +import platform +import plistlib +import re +import secrets +import statistics +import subprocess +import time +import uuid + + +ARMS = ("baseline", "candidate") +METRICS = ("elapsedNs", "threadCpuNs") + + +def run(*arguments, env=None, timeout=60): + return subprocess.check_output(arguments, text=True, env=env, timeout=timeout).strip() + + +def simctl(*arguments, **kwargs): + return run("xcrun", "simctl", *arguments, **kwargs) + + +def write_json(path, value): + with path.open("w") as stream: + json.dump(value, stream, indent=2, allow_nan=False) + stream.write("\n") + + +def identify_app(app, revision, name): + if re.fullmatch(r"[a-f0-9]{40}", revision) is None: + raise ValueError(f"{app}: expected a full Git commit SHA") + with (app / "Info.plist").open("rb") as stream: + info = plistlib.load(stream) + if "iPhoneSimulator" not in info["CFBundleSupportedPlatforms"]: + raise ValueError(f"{app}: expected an iOS Simulator build") + if info.get("NitroPerfConfiguration") != "Release" or info.get("NitroPerfRevision") != revision: + raise ValueError(f"{app}: fixture is not a Release build of {revision}") + bundle = info["CFBundleIdentifier"] + if bundle != f"com.margelo.nitroui.performance.{name}": + raise ValueError(f"{app}: unexpected {name} bundle identifier {bundle}") + return {"bundleID": bundle, "revision": revision} + + +def simulator_metadata(device): + inventory = simctl("list", "devices", "--json", timeout=180) + devices = json.loads(inventory)["devices"] + for runtime, entries in devices.items(): + for entry in entries: + if entry["udid"] == device and entry["state"] == "Booted" and entry["isAvailable"]: + return {"udid": device, "name": entry["name"], "type": entry["deviceTypeIdentifier"], "runtime": runtime} + raise ValueError(f"Expected booted simulator {device}") + + +def rank_interval(values, comparisons): + # Invert the two-sided exact sign test for the population median. Bonferroni + # covers every prespecified metric and look without assuming independence between them. + n = len(values) + rank = 0 + tail = 0 + for i in range(n // 2): + tail += math.comb(n, i) + if 40 * comparisons * tail > 2 ** n: + break + rank += 1 + if not rank: + return None + ordered = sorted(values) + return [ordered[rank - 1], ordered[-rank]] + + +def percent(log_ratio): + return 100 * math.expm1(log_ratio) + + +def metric_summary(pairs, metric, comparisons): + baseline = [pair["baseline"][metric] for pair in pairs] + candidate = [pair["candidate"][metric] for pair in pairs] + changes = [math.log(b / a) for a, b in zip(baseline, candidate)] + # A two-pair block includes one launch in each position for both apps. + blocks = [(ab + ba) / 2 for ab, ba in zip(changes[::2], changes[1::2])] + change = percent(statistics.median(blocks)) + interval = rank_interval(blocks, comparisons) + result = { + "baselineMedianNs": statistics.median(baseline), + "candidateMedianNs": statistics.median(candidate), + "changePct": change, "intervalPct": None, "radiusPp": None, + } + if interval: + low, high = map(percent, interval) + result["intervalPct"] = [low, high] + result["radiusPp"] = max(change - low, high - change) + return result + + +def planned_looks(count): + return [look for look in (16, 32, 64) if look < count] + [count] + + +def process_alive(pid): + # CoreSimulator apps share the macOS host's PID namespace. + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + return True + + +def wait_for_exit(pid): + deadline = time.monotonic() + 60 + while process_alive(pid): + if time.monotonic() > deadline: + raise TimeoutError(f"Simulator app PID {pid} did not exit after writing its result") + time.sleep(0.05) + + +def app_sample(device, arm, container, sample_id): + env = os.environ.copy() + env["SIMCTL_CHILD_NITRO_PERF_SAMPLE"] = sample_id + env["SIMCTL_CHILD_NITRO_PERF_LAYOUT_PASSES"] = str(arm["iterations"]) + launch = simctl("launch", device, arm["bundleID"], env=env, timeout=180) + bundle = re.escape(arm["bundleID"]) + match = re.fullmatch(rf"{bundle}: ([1-9][0-9]*)", launch) + if not match: + raise ValueError(f"Expected launched app PID from simctl, got {launch!r}") + pid = int(match[1]) + output = container / "Documents" / f"nitro-perf-{sample_id}.json" + deadline = time.monotonic() + 60 + while True: + alive = process_alive(pid) + if output.exists(): + break + if not alive: + raise ValueError(f"Simulator app PID {pid} exited before writing sample {sample_id}") + if time.monotonic() > deadline: + raise TimeoutError(f"{arm['bundleID']} did not finish sample {sample_id} within 60 seconds") + time.sleep(0.1) + if output.is_symlink() or output.stat().st_size > 65536: + raise ValueError(f"Unexpected result file for sample {sample_id}") + with output.open() as stream: + report = json.load(stream) + return report, pid + + +def precision(looks): + # A descriptive precision target, evaluated at the same planned looks used for inference. + target = 5.0 + for look in looks: + radii = [metric["radiusPp"] for metric in look["metrics"].values()] + if all(radius is not None and radius <= target for radius in radii): + return {"targetRadiusPp": target, "firstPairs": look["pairs"], "elapsedSeconds": look["elapsedSeconds"]} + return {"targetRadiusPp": target, "firstPairs": None, "elapsedSeconds": None} + + +def markdown(session, looks, achieved): + rows = [ + "## iOS Simulator Release comparison", "", + f"Baseline `{session['arms']['baseline']['revision'][:12]}`, candidate `{session['arms']['candidate']['revision'][:12]}`.", + f"{session['mode']} on {session['simulator']['name']}, `{session['simulator']['runtime']}`, {session['host']['arch']}.", "", + "| Pairs | Measured time | Metric | Baseline median | Candidate median | Paired change | Simultaneous 95% interval |", + "|---:|---:|---|---:|---:|---:|---:|", + ] + for look in looks: + for name, result in look["metrics"].items(): + bounds = result["intervalPct"] + interval = f"[{bounds[0]:+.2f}%, {bounds[1]:+.2f}%]" if bounds else "insufficient pairs" + rows.append(f"| {look['pairs']} | {look['elapsedSeconds']:.1f} s | {name} | " + f"{result['baselineMedianNs'] / 1e6:.3f} ms | {result['candidateMedianNs'] / 1e6:.3f} ms | " + f"{result['changePct']:+.2f}% | {interval} |") + if achieved["firstPairs"] is None: + rows.extend(["", "At the planned looks, at least one metric still exceeded the 5 percentage point precision target or had no finite interval."]) + else: + rows.extend(["", f"Both intervals first reached a radius of 5 percentage points or less at {achieved['firstPairs']} pairs " + f"({achieved['elapsedSeconds']:.1f} s of measured launches)."]) + rows.extend(["", "Each complete AB/BA block contributes one mean log ratio. The change is the median across blocks. " + "The intervals assume independent blocks with a common median and cover the listed metrics and planned looks together. " + "Measured time excludes installation and warmup."]) + return "\n".join(rows) + "\n" + + +def validate(report, sample_id, iterations, pid): + if not isinstance(report, dict): + raise ValueError(f"Expected a JSON object in sample {sample_id}") + if report.get("error"): + raise ValueError(f"Fixture failed sample {sample_id}: {report['error']}") + required = { + "sample": sample_id, "processId": pid, "workload": "layout-update", "verified": True, "thread": "main", + "leafCount": 256, "iterations": iterations, "appliedLeafFrames": 256 * iterations, + "countersAvailable": False, "counterErrno": errno.ENOTSUP, + } + for key, expected in required.items(): + value = report.get(key) + if type(value) is not type(expected) or value != expected: + raise ValueError(f"Invalid {key} in sample {sample_id}") + tid = report.get("threadId") + if type(tid) is not int or tid <= 0: + raise ValueError(f"Missing thread ID in sample {sample_id}") + metrics = report["metrics"] + if set(metrics) != set(METRICS): + raise ValueError(f"Unexpected metrics in sample {sample_id}") + for name in METRICS: + if type(metrics[name]) is not int or metrics[name] <= 0: + raise ValueError(f"Invalid {name} in sample {sample_id}") + + +def session_plan(args): + arms = { + "baseline": identify_app(args.baseline, args.baseline_revision, "baseline"), + "candidate": identify_app(args.candidate, args.candidate_revision, "candidate"), + } + comparing_revisions = args.baseline_revision != args.candidate_revision + arms["baseline"]["iterations"] = 128 + arms["candidate"]["iterations"] = 128 + mode = "Revision comparison" if comparing_revisions else "A/A calibration" + if args.positive_control: + if comparing_revisions: + raise ValueError("The positive control requires identical source revisions") + arms["candidate"]["iterations"] = 136 + mode = "Positive control (136 vs 128 layout passes, +6.25% candidate work)" + github = {} + for key in ("GITHUB_RUN_ID", "GITHUB_RUN_ATTEMPT", "GITHUB_JOB", "GITHUB_REPOSITORY", "GITHUB_SHA", + "RUNNER_ENVIRONMENT", "RUNNER_OS", "RUNNER_ARCH", "ImageOS", "ImageVersion"): + if key in os.environ: + github[key] = os.environ[key] + return { + "mode": mode, "workload": "layout-update", "thread": "main", "metrics": list(METRICS), + "pairs": args.pairs, "looks": planned_looks(args.pairs), "warmupPairs": 2, "first": secrets.choice(ARMS), + "arms": arms, + "simulator": simulator_metadata(args.device), "github": github, "host": { + "arch": platform.machine(), "macOS": run("sw_vers", "-productVersion"), + "hostBuild": run("sw_vers", "-buildVersion"), "xcode": run("xcodebuild", "-version"), + "cpu": run("sysctl", "-n", "machdep.cpu.brand_string"), "logicalCPUs": int(run("sysctl", "-n", "hw.logicalcpu")), + }, + "startedAt": datetime.now(timezone.utc).isoformat(), "completedPairs": 0, "status": "running", + } + + +def compare(args): + if args.pairs < 2 or args.pairs % 2: + raise ValueError("Choose an even number of at least two measured pairs") + session = session_plan(args) + args.output.mkdir(parents=True, exist_ok=False) + state_path = args.output / "session.json" + write_json(state_path, session) + containers = {} + measurements = [] + summaries = [] + try: + for name in ARMS: + app = getattr(args, name) + simctl("install", args.device, str(app), timeout=180) + bundle = session["arms"][name]["bundleID"] + path = simctl("get_app_container", args.device, bundle, "data") + containers[name] = Path(path) + first_order = ARMS if session["first"] == "baseline" else ARMS[::-1] + comparisons = len(METRICS) * len(session["looks"]) + with (args.output / "raw.jsonl").open("x") as raw: + for phase, count in (("warmup", session["warmupPairs"]), ("measurement", args.pairs)): + start = time.monotonic() + for pair in range(1, count + 1): + order = first_order if pair % 2 else first_order[::-1] + metrics = {} + for position, name in enumerate(order, 1): + sample_id = str(uuid.uuid4()) + arm = session["arms"][name] + report, pid = app_sample(args.device, arm, containers[name], sample_id) + validate(report, sample_id, arm["iterations"], pid) + row = {"phase": phase, "pair": pair, "position": position, "variant": name, + "completedSeconds": time.monotonic() - start, "report": report} + raw.write(json.dumps(row, allow_nan=False) + "\n") + raw.flush() + wait_for_exit(pid) + metrics[name] = report["metrics"] + if phase == "measurement": + measurements.append(metrics) + session["completedPairs"] = pair + if pair in session["looks"]: + summaries.append({ + "pairs": pair, + "elapsedSeconds": time.monotonic() - start, + "metrics": {name: metric_summary(measurements, name, comparisons) for name in METRICS}, + }) + print(f"Completed {pair}/{args.pairs} pairs", flush=True) + achieved = precision(summaries) + write_json(args.output / "results.json", {"familywiseConfidence": 0.95, "looks": summaries, "precision": achieved}) + summary = markdown(session, summaries, achieved) + (args.output / "summary.md").write_text(summary) + print(summary) + session["status"] = "completed" + except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as error: + session["status"] = "failed" + session["error"] = str(error) + raise + finally: + session["finishedAt"] = datetime.now(timezone.utc).isoformat() + write_json(state_path, session) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--device", required=True, help="UDID of one booted simulator") + for name in ARMS: + parser.add_argument("--" + name, type=Path, required=True, help="Built simulator .app bundle") + parser.add_argument("--" + name + "-revision", required=True, help="Full source commit embedded in the bundle") + parser.add_argument("--pairs", type=int, default=32) + parser.add_argument("--positive-control", action="store_true", help="Run 136 candidate layout passes against 128 on the identical baseline") + parser.add_argument("--output", type=Path, required=True, help="New directory for raw samples, session metadata and comparison") + args = parser.parse_args() + try: + compare(args) + except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as error: + parser.exit(1, f"{error}\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/performance/ios/fixture/AppDelegate.swift b/scripts/performance/ios/fixture/AppDelegate.swift new file mode 100644 index 000000000..63493dcc9 --- /dev/null +++ b/scripts/performance/ios/fixture/AppDelegate.swift @@ -0,0 +1,4 @@ +import UIKit + +@main +final class AppDelegate: UIResponder, UIApplicationDelegate {} diff --git a/scripts/performance/ios/fixture/CMakeLists.txt b/scripts/performance/ios/fixture/CMakeLists.txt new file mode 100644 index 000000000..87667c830 --- /dev/null +++ b/scripts/performance/ios/fixture/CMakeLists.txt @@ -0,0 +1,24 @@ +cmake_minimum_required(VERSION 3.22) +project(NitroPerf LANGUAGES C CXX OBJCXX Swift) + +add_subdirectory("${NITRO_SOURCE_ROOT}/packages/nitro-ui-layout" layout) +add_subdirectory("${NITRO_SOURCE_ROOT}/packages/nitro-ui-layout-yoga" layout-yoga) + +add_executable(NitroPerf MACOSX_BUNDLE + AppDelegate.swift + SceneDelegate.swift + LayoutWorkload.mm + "${THREAD_BENCHMARK_SOURCE}" +) +target_include_directories(NitroPerf PRIVATE "${NITRO_SOURCE_ROOT}/packages/nitro-ui-layout/include") +target_link_libraries(NitroPerf PRIVATE NitroLayoutProvider "-framework UIKit" "-lc++") +set_target_properties(NitroPerf PROPERTIES + MACOSX_BUNDLE_INFO_PLIST "${CMAKE_CURRENT_SOURCE_DIR}/Info.plist.in" + RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}/app" + XCODE_ATTRIBUTE_PRODUCT_BUNDLE_IDENTIFIER "com.margelo.nitroui.performance.${NITRO_VARIANT}" + XCODE_ATTRIBUTE_CLANG_ENABLE_OBJC_ARC YES + XCODE_ATTRIBUTE_SWIFT_OBJC_BRIDGING_HEADER "${CMAKE_CURRENT_SOURCE_DIR}/LayoutWorkload.h" + XCODE_ATTRIBUTE_TARGETED_DEVICE_FAMILY "1,2" + XCODE_ATTRIBUTE_SWIFT_VERSION 5.0 + XCODE_ATTRIBUTE_SWIFT_OPTIMIZATION_LEVEL "-O" +) diff --git a/scripts/performance/ios/fixture/Info.plist.in b/scripts/performance/ios/fixture/Info.plist.in new file mode 100644 index 000000000..7ef5b96d8 --- /dev/null +++ b/scripts/performance/ios/fixture/Info.plist.in @@ -0,0 +1,29 @@ + + + + + CFBundleExecutable$(EXECUTABLE_NAME) + CFBundleIdentifier$(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleNameNitroPerf + CFBundlePackageTypeAPPL + CFBundleVersion1 + CFBundleShortVersionString1.0 + NitroPerfConfiguration$(CONFIGURATION) + NitroPerfRevision${NITRO_REVISION} + UILaunchScreen + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneConfigurationNameBenchmark + UISceneDelegateClassName$(PRODUCT_MODULE_NAME).SceneDelegate + + + + + + diff --git a/scripts/performance/ios/fixture/LayoutWorkload.h b/scripts/performance/ios/fixture/LayoutWorkload.h new file mode 100644 index 000000000..cf052b692 --- /dev/null +++ b/scripts/performance/ios/fixture/LayoutWorkload.h @@ -0,0 +1,13 @@ +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface LayoutWorkload : NSObject +- (instancetype)initWithContainer:(UIView *)container; +- (void)runIterations:(NSUInteger)iterations; +@property(nonatomic, readonly) NSUInteger leafCount; +@property(nonatomic, readonly) NSUInteger appliedLeafFrames; +@property(nonatomic, readonly) BOOL hasExpectedFrames; +@end + +NS_ASSUME_NONNULL_END diff --git a/scripts/performance/ios/fixture/LayoutWorkload.mm b/scripts/performance/ios/fixture/LayoutWorkload.mm new file mode 100644 index 000000000..d5bccf8ad --- /dev/null +++ b/scripts/performance/ios/fixture/LayoutWorkload.mm @@ -0,0 +1,101 @@ +#import "LayoutWorkload.h" +#include +#include + +static constexpr NSUInteger RowCount = 32; +static constexpr NSUInteger ColumnCount = 8; +static constexpr NSUInteger LeafCount = RowCount * ColumnCount; +static constexpr CGFloat RowHeight = 16; +static constexpr CGFloat TreeWidth = 320; + +@interface LayoutItem : UIView +@property(nonatomic) NSUInteger applications; +@end +@implementation LayoutItem +@end + +static void applyFrame(void *context, float x, float y, float width, float height) { + LayoutItem *view = (__bridge LayoutItem *)context; + view.frame = CGRectMake(x, y, width, height); + view.applications += 1; +} + +@implementation LayoutWorkload { + NLNodeRef _root; + std::array _rows; + std::array _leaves; + NSArray *_rowViews; + NSArray *_leafViews; +} + +- (instancetype)initWithContainer:(UIView *)container { + self = [super init]; + if (self) { + _root = NLCreate(1); + NLSetFlexDirection(_root, NLColumn); + NSMutableArray *rowViews = [NSMutableArray arrayWithCapacity:RowCount]; + NSMutableArray *leafViews = [NSMutableArray arrayWithCapacity:LeafCount]; + for (NSUInteger row = 0; row < RowCount; row++) { + NLNodeRef rowNode = NLCreate(1); + _rows[row] = rowNode; + NLSetFlexDirection(rowNode, NLRow); + NLSetHeight(rowNode, RowHeight, NLPoint); + NLAppendChild(_root, rowNode); + LayoutItem *rowView = [LayoutItem new]; + [container addSubview:rowView]; + [rowViews addObject:rowView]; + NLSetFrameCallback(rowNode, (__bridge void *)rowView, applyFrame); + for (NSUInteger column = 0; column < ColumnCount; column++) { + NLNodeRef leaf = NLCreate(1); + _leaves[row * ColumnCount + column] = leaf; + NLAppendChild(rowNode, leaf); + LayoutItem *view = [LayoutItem new]; + [rowView addSubview:view]; + [leafViews addObject:view]; + NLSetFrameCallback(leaf, (__bridge void *)view, applyFrame); + } + } + _rowViews = rowViews; + _leafViews = leafViews; + } + return self; +} + +- (void)dealloc { + for (auto leaf : _leaves) NLDestroy(leaf); + for (auto row : _rows) NLDestroy(row); + NLDestroy(_root); +} + +- (void)runIterations:(NSUInteger)iterations { + for (NSUInteger i = 0; i < iterations; i++) { + const float width = i % 2 == 0 ? 24 : 32; + for (auto leaf : _leaves) NLSetWidth(leaf, width, NLPoint); + NLSolve(_root, TreeWidth, RowCount * RowHeight); + NLApplyLayout(_root); + } +} + +- (NSUInteger)leafCount { + return LeafCount; +} + +- (NSUInteger)appliedLeafFrames { + NSUInteger count = 0; + for (LayoutItem *view in _leafViews) count += view.applications; + return count; +} + +- (BOOL)hasExpectedFrames { + for (NSUInteger row = 0; row < RowCount; row++) { + const CGRect expectedRow = CGRectMake(0, row * RowHeight, TreeWidth, RowHeight); + if (!CGRectEqualToRect(_rowViews[row].frame, expectedRow)) return NO; + for (NSUInteger col = 0; col < ColumnCount; col++) { + const CGRect expectedLeaf = CGRectMake(col * 32, 0, 32, RowHeight); + LayoutItem *leaf = _leafViews[row * ColumnCount + col]; + if (!CGRectEqualToRect(leaf.frame, expectedLeaf)) return NO; + } + } + return YES; +} +@end diff --git a/scripts/performance/ios/fixture/SceneDelegate.swift b/scripts/performance/ios/fixture/SceneDelegate.swift new file mode 100644 index 000000000..48c3c1981 --- /dev/null +++ b/scripts/performance/ios/fixture/SceneDelegate.swift @@ -0,0 +1,74 @@ +import UIKit + +final class SceneDelegate: UIResponder, UIWindowSceneDelegate { + var window: UIWindow? + private var started = false + + func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options: UIScene.ConnectionOptions) { + guard let scene = scene as? UIWindowScene else { return } + let window = UIWindow(windowScene: scene) + window.rootViewController = UIViewController() + self.window = window + window.makeKeyAndVisible() + } + + func sceneDidBecomeActive(_ scene: UIScene) { + guard !started, let container = window?.rootViewController?.view else { return } + let environment = ProcessInfo.processInfo.environment + guard let sample = environment["NITRO_PERF_SAMPLE"], UUID(uuidString: sample) != nil else { return } + started = true + let documents = URL.documentsDirectory + let destination = documents.appendingPathComponent("nitro-perf-\(sample).json") + let result: [String: Any] + let status: Int32 + do { + guard let raw = environment["NITRO_PERF_LAYOUT_PASSES"], let iterations = UInt(raw), + iterations == 128 || iterations == 136 else { + throw BenchmarkError.invalidLayoutPasses + } + result = try measure(sample: sample, iterations: iterations, container: container) + status = EXIT_SUCCESS + } catch { + result = ["sample": sample, "error": String(describing: error)] + status = EXIT_FAILURE + } + do { + let data = try JSONSerialization.data(withJSONObject: result) + try data.write(to: destination, options: .atomic) + } catch { + NSLog("Cannot write benchmark result at %@: %@", destination.path, error.localizedDescription) + exit(EXIT_FAILURE) + } + exit(status) + } + + private func measure(sample: String, iterations: UInt, container: UIView) throws -> [String: Any] { + let name = "layout-update" + let workload = LayoutWorkload(container: container) + workload.runIterations(4) + let before = workload.appliedLeafFrames + let window = try ThreadBenchmark(name: name) + workload.runIterations(iterations) + let result = try window.end() + let applied = workload.appliedLeafFrames - before + let expected = workload.leafCount * iterations + guard workload.hasExpectedFrames, applied == expected else { + throw BenchmarkError.incorrectLayout(applied: applied, expected: expected) + } + let elapsedNs = result.elapsedMs * 1_000_000 + let threadCpuNs = result.threadCpuMs * 1_000_000 + return [ + "sample": sample, "processId": ProcessInfo.processInfo.processIdentifier, + "workload": name, "thread": "main", "threadId": result.threadId, + "metrics": ["elapsedNs": Int64(elapsedNs.rounded()), "threadCpuNs": Int64(threadCpuNs.rounded())], + "countersAvailable": result.countersAvailable, "counterErrno": result.counterErrno, + "iterations": iterations, "leafCount": workload.leafCount, + "appliedLeafFrames": applied, "verified": true, + ] + } + + private enum BenchmarkError: Error { + case invalidLayoutPasses + case incorrectLayout(applied: UInt, expected: UInt) + } +}