Skip to content

CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息

feat: 添加自动化性能采集与可视化报告

Bob550a4c25e839
diff --git a/Scripts/performance/README.md b/Scripts/performance/README.md
new file mode 100644
index 0000000..5bd7e82
--- /dev/null
+++ b/Scripts/performance/README.md
@@ -0,0 +1,175 @@
+# App 性能测试与报告
+
+通过 Instruments 采集运行中 macOS App 主进程的 CPU、调用栈、内存、线程、唤醒、磁盘活动和热状态,自动生成单文件 HTML 报告。默认测试 `/Applications/CodexBar.app`,通过 `--app` 可指定其他 App。
+
+## 快速开始
+
+准备好以下环境:
+
+- macOS、完整 Xcode、Python `3.11+`
+- `xcode-select -p` 指向 Xcode 的 `Contents/Developer` 目录
+- 被测 App 已启动,终端具备 Instruments 采集权限
+
+在仓库根目录运行:
+
+```sh
+python3 -B Scripts/performance/run.py --preset standard
+```
+
+脚本完成预检、预热、分阶段采集、数据解析和报告生成,结束后在终端打印 `report.html` 路径。采集直接附加到现有 App 进程。按 `Ctrl-C` 可停止采集并保存已有结果,App 继续运行。
+
+默认输出目录为 `Build/Performance/YYYYMMDD-HHMMSS`。`Scripts/build.sh` 会清理 `Build`,需要长期保留的结果请指定其他目录:
+
+```sh
+python3 -B Scripts/performance/run.py \
+ --preset standard \
+ --output PerformanceResults/idle-01 \
+ --workload '闲置:面板关闭,无手动操作,接通电源'
+```
+
+采集输出目录必须尚未存在。测试期间保持单个 Instruments 采集任务,并将构建等高负载工作安排在采集结束后。
+
+## 选择测试时长
+
+| 预设 | 预热 | CPU 采集 | 资源观察 | 后续观察 | 累计采集 |
+|---|---:|---:|---:|---:|---:|
+| `quick` | 5 秒 | 2 × 20 秒 | 60 秒 | 20 秒 | 2 分钟 |
+| `standard` | 20 秒 | 3 × 60 秒 | 300 秒 | 60 秒 | 9 分钟 |
+| `extended` | 30 秒 | 3 × 120 秒 | 900 秒 | 120 秒 | 23 分钟 |
+
+- `quick`:检查采集流程,快速观察操作时的资源变化
+- `standard`:日常性能评估,观察重复采样与后台活动
+- `extended`:观察更长时间的内存变化和周期性任务
+
+实际运行时间还包括 Instruments 初始化、保存和导出。`cpu-*` 阶段使用 `Time Profiler + Activity Monitor`,同时采集调用栈、资源指标和 Hangs;`soak`、`settle` 阶段使用 `Activity Monitor` 继续观察资源变化。
+
+## 组织测试场景
+
+采集和报告由脚本自动执行,界面操作由测试者执行。用 `--workload` 记录场景、操作步骤、活动任务和电源状态。
+
+| 场景 | 执行方式 | 重点观察 |
+|---|---|---|
+| 闲置 | 关闭面板,保持后台设置一致,采集期间不手动操作 | CPU 常态与突增、唤醒频率、内存基线 |
+| 高频操作 | 按固定顺序反复打开面板、切换页面和滚动列表 | 主线程热点、CPU 峰值、Hangs、内存峰值 |
+| 操作后闲置 | 记录停止操作的时间,随后保持面板关闭 | CPU 回落、内存释放、后台活动 |
+
+比较两个版本时,使用相同的预设和操作步骤,并记录各次结果。比较闲置与高频操作时,分别保存报告,按阶段查看差异。
+
+## 参数
+
+| 参数 | 用途 |
+|---|---|
+| `--app` | 被测 App 路径,默认 `/Applications/CodexBar.app` |
+| `--pid` | 指定进程;存在多个匹配实例时使用 |
+| `--preset` | `quick`、`standard` 或 `extended`,默认 `standard` |
+| `--output` | 采集模式指定新目录;`--render` 模式指定 HTML 文件路径 |
+| `--workload` | 写入报告的测试场景说明 |
+| `--baseline` | 指定同场景历史 `results.json`,采集后计算阶段差值 |
+| `--cpu-mean-budget` | 各阶段平均 CPU 上限,单位为 `%` |
+| `--footprint-budget` | 各阶段内存 footprint 峰值上限,单位为 `MiB` |
+| `--render` | 从已有 JSON 生成 HTML |
+
+例如,将平均 CPU 上限设为 `5%`、内存峰值上限设为 `512 MiB`:
+
+```sh
+python3 -B Scripts/performance/run.py \
+ --cpu-mean-budget 5 \
+ --footprint-budget 512
+```
+
+上限值须为有限正数。脚本逐阶段检查预算,超出项写入报告。
+
+## 阅读报告
+
+报告按数据总览、阶段对比、唤醒与磁盘、运行曲线、CPU 热点、事件与热状态、采集记录组织。
+
+| 数据 | 图表与读数方式 |
+|---|---|
+| CPU、footprint、RSS、压缩内存 | 分别绘制趋势图;同一指标各阶段共用纵轴,标注峰值 |
+| 线程数量 | 阶梯图 |
+| 内存最小值、中位数、峰值 | 区间图 |
+| 内存首尾窗口中位数 | 哑铃图,标注增减量 |
+| 主线程采样占比 | 百分比堆叠条 |
+| 调用栈热点 | 按采样权重排列的横向条形图 |
+
+趋势图支持鼠标游标和键盘滑块读数,采样间隔超过 5 秒时断开连线。报告支持深浅主题、展开热点、导出 JSON 和打印,可离线打开。中文使用苹果系统字体,英文和数字使用本机安装的 `MesloLGS NF`。
+
+### 指标含义
+
+- **CPU**:累计 CPU 时间增量除以观测时长,`100%` 表示占用一个逻辑核心。平均值按有效观测时长加权,P50、P95 为区间 CPU 使用率样本的线性插值分位数,峰值为区间使用率最大值
+- **内存**:分别展示 physical footprint、RSS 和压缩内存,单位为 `MiB`。趋势斜率由阶段样本作最小二乘拟合,单位为 `MiB/min`。首尾窗口长度取 60 秒与阶段跨度四分之一中的较小值
+- **唤醒与磁盘**:累计计数取阶段末值减去初值,平均速率除以阶段资源观测时长
+- **CPU 热点**:按调用栈采样权重统计,单位为 `ms`。叶节点表示栈顶函数,调用链权重包含子调用,同一调用栈中的递归符号计一次
+- **Hangs**:按导出的事件计数,检测配置保存在阶段数据的 `hang_settings` 中。空表记为 `0`,缺失数据展示为 `N/A`
+- **App 文件指纹**:被测 App 主可执行文件的 SHA-256;`Mach-O UUID` 标识各架构二进制,用于匹配 dSYM
+
+### 与历史结果比较
+
+```sh
+python3 -B Scripts/performance/run.py \
+ --preset standard \
+ --output PerformanceResults/idle-02 \
+ --workload '闲置:面板关闭,无手动操作,接通电源' \
+ --baseline PerformanceResults/idle-01/results.json
+```
+
+脚本核对 App 的 bundle ID、系统、芯片、架构、核心数、内存容量、电源来源、Instruments、场景说明、预设、预算、数据格式和阶段计划。两次采集均完整且上述条件一致时,报告展示各阶段平均 CPU 差值和 footprint 中位数差值;条件不匹配时列出差异字段。App 版本可以不同。
+
+## 输出文件与重新生成报告
+
+| 文件 | 内容 |
+|---|---|
+| `report.html` | 内嵌样式、图表、交互脚本和统计 JSON 的报告 |
+| `results.json` | 完整统计结果、采集状态、命令及日志索引 |
+| `schemas.json` | 当前 Xcode 的 XML 列定义 |
+| `tool-source/` | 采集启动时的工具源码快照,文件哈希保存在 `results.json` |
+| `*.trace` | 可用 Instruments 打开的原始记录 |
+| `*-toc.xml`、各 schema 的 XML | trace 目录信息与导出的采样数据 |
+| `*.log` | 各条采集、导出命令的日志 |
+
+修改报告模板后,用已有结果重新生成 HTML:
+
+```sh
+python3 -B Scripts/performance/run.py \
+ --render PerformanceResults/idle-01/results.json
+```
+
+默认更新 JSON 同目录的 `report.html`。指定另一个文件可保留原报告:
+
+```sh
+python3 -B Scripts/performance/run.py \
+ --render PerformanceResults/idle-01/results.json \
+ --output PerformanceResults/idle-01/report-updated.html
+```
+
+报告页面导出的统计 JSON 也可传给 `--render`。
+
+## 采集检查与排错
+
+阶段有效须满足以下条件:
+
+- 被测可执行文件、PID 和进程启动时间保持一致
+- 记录成功,时长达到计划的 `90%`
+- 至少 3 个资源样本,资源观测跨度达到计划的 `80%`
+- 最大资源采样间隔不超过 5 秒
+- CPU 计数覆盖率至少 `95%`,累计计数不回退
+- 成功取得 footprint;CPU 阶段成功解析 `time-profile` 表
+
+| 退出码 | 含义 |
+|---|---|
+| `0` | 采集完整,已配置的预算检查通过 |
+| `2` | 参数、环境、采集、解析、质量检查或结果保存失败 |
+| `3` | 采集完整,超过配置预算 |
+| `130` | 操作者中断采集 |
+
+根据终端输出、报告中的错误信息和对应阶段日志排查:
+
+| 现象 | 处理方式 |
+|---|---|
+| 找不到 App 进程或匹配到多个实例 | 启动目标 App,核对 `--app`,必要时指定 `--pid` |
+| 缺少模板或列定义 | 检查 `xcode-select -p`,确认使用完整 Xcode |
+| Instruments 附加失败 | 查看 `*-record.log` 中的权限或进程错误,处理后重新采集 |
+| 输出目录不存在或被替换 | 查看是否执行了构建清理,将后续输出放到 `Build` 以外 |
+| 热点只显示地址 | 使用与 `Mach-O UUID` 匹配的 dSYM,在 Instruments 中符号化 |
+
+最终保存失败时,脚本会尝试将内存中已有的统计数据和原始错误写入系统临时目录 `codexbar-performance-recovery-*`,并打印报告路径;若恢复保存也失败,终端会输出对应错误。
diff --git a/Scripts/performance/analyze.py b/Scripts/performance/analyze.py
new file mode 100644
index 0000000..f6bd000
--- /dev/null
+++ b/Scripts/performance/analyze.py
@@ -0,0 +1,189 @@
+"""Decode xctrace XML using the schemas shipped with the recording Xcode"""
+
+import collections
+import math
+import statistics
+import xml.etree.ElementTree as ET
+
+
+def percentile(values, fraction):
+ if not values:
+ return None
+ values = sorted(values)
+ position = (len(values) - 1) * fraction
+ lower = math.floor(position)
+ upper = math.ceil(position)
+ return values[lower] + (values[upper] - values[lower]) * (position - lower)
+
+
+class Table:
+ def __init__(self, path, columns):
+ self.root = ET.parse(path).getroot()
+ self.ids = {e.get("id"): e for e in self.root.iter() if e.get("id")}
+ self.columns = columns
+
+ def resolve(self, element):
+ if element is None:
+ return None
+ return self.ids[element.get("ref")] if element.get("ref") else element
+
+ def number(self, element):
+ element = self.resolve(element)
+ if element is None or element.tag == "sentinel":
+ return None
+ try:
+ value = float(element.text)
+ return value if math.isfinite(value) else None
+ except (ValueError, TypeError):
+ return None
+
+ def label(self, element):
+ element = self.resolve(element)
+ return "" if element is None else element.get("fmt", element.text or "")
+
+ def rows(self):
+ for row in self.root.iter("row"):
+ if len(row) != len(self.columns):
+ raise ValueError(f"Schema mismatch: expected {len(self.columns)} columns, got {len(row)}")
+ yield dict(zip(self.columns, row))
+
+
+def resource_summary(table, pid):
+ points = []
+ for row in table.rows():
+ if table.number(row.get("pid")) != pid:
+ continue
+ point = {key: table.number(value) for key, value in row.items()}
+ if point.get("start") is not None:
+ points.append(point)
+ points.sort(key=lambda p: p["start"])
+ if len(points) < 3:
+ raise ValueError("Fewer than 3 target resource samples")
+ series, errors = [], []
+ previous = None
+ for point in points:
+ timestamp = point["start"] / 1e9
+ item = {"t": timestamp, "cpu": None, "dt": None}
+ for source, destination in [("memory-physical-footprint", "footprint"),
+ ("memory-real", "rss"), ("memory-compressed", "compressed")]:
+ value = point.get(source)
+ item[destination] = value / 2 ** 20 if value is not None else None
+ item["threads"] = point.get("thread-count")
+ if previous is not None:
+ dt = (point["start"] - previous["start"]) / 1e9
+ current_cpu, last_cpu = point.get("cpu-total"), previous.get("cpu-total")
+ if dt > 0 and current_cpu is not None and last_cpu is not None:
+ delta = (current_cpu - last_cpu) / 1e9
+ if delta < 0:
+ errors.append("CPU counter decreased; possible process reset or invalid data")
+ else:
+ item.update(cpu=100 * delta / dt, dt=dt)
+ series.append(item)
+ previous = point
+ span = series[-1]["t"] - series[0]["t"]
+ if span <= 0:
+ raise ValueError("Resource sample time did not advance")
+ cpu_points = [p for p in series if p["cpu"] is not None]
+ observed_seconds = sum(p["dt"] for p in cpu_points)
+ cpu = [p["cpu"] for p in cpu_points]
+ result = {"samples": len(series), "span_s": span, "series": series, "errors": errors,
+ "max_gap_s": max(b["t"] - a["t"] for a, b in zip(series, series[1:])),
+ "cpu_coverage": observed_seconds / span,
+ "cpu_mean": sum(p["cpu"] * p["dt"] for p in cpu_points) / observed_seconds if observed_seconds else None,
+ "cpu_p50": percentile(cpu, .5), "cpu_p95": percentile(cpu, .95),
+ "cpu_peak": max(cpu) if cpu else None}
+ for key in ["footprint", "rss", "compressed", "threads"]:
+ values = [p[key] for p in series if p[key] is not None]
+ result[key] = {"first": values[0], "last": values[-1], "min": min(values),
+ "max": max(values), "median": statistics.median(values)} if values else None
+ for key, name in [("idle-wakeups", "wakeups"), ("disk-bytes-read", "read_bytes"),
+ ("disk-bytes-written", "written_bytes")]:
+ first, last = points[0].get(key), points[-1].get(key)
+ result[name] = last - first if first is not None and last is not None and last >= first else None
+ result[name + "_per_s"] = result[name] / span if result[name] is not None else None
+ footprint = [(p["t"], p["footprint"]) for p in series if p["footprint"] is not None]
+ if len(footprint) >= 3:
+ xs, ys = zip(*footprint)
+ xmean, ymean = statistics.mean(xs), statistics.mean(ys)
+ denominator = sum((x - xmean) ** 2 for x in xs)
+ slope = sum((x - xmean) * (y - ymean) for x, y in footprint) / denominator if denominator else 0
+ window = min(60, span / 4)
+ head = [y for x, y in footprint if x <= xs[0] + window]
+ tail = [y for x, y in footprint if x >= xs[-1] - window]
+ result["memory_trend"] = {"slope_mib_min": slope * 60, "window_s": window,
+ "head_median": statistics.median(head), "tail_median": statistics.median(tail),
+ "delta_mib": statistics.median(tail) - statistics.median(head),
+ "long_enough": span >= 240}
+ return result
+
+
+def profile_summary(table, pid):
+ total = main = missing = app_weight = app_named = 0
+ leaf, inclusive, binaries, seconds = (collections.Counter() for _ in range(4))
+ for row in table.rows():
+ process = table.resolve(row.get("process"))
+ process_pid = table.number(process.find("pid")) if process is not None else None
+ if process_pid != pid:
+ continue
+ weight = table.number(row.get("weight"))
+ if weight is None:
+ continue
+ weight /= 1e6
+ total += weight
+ thread = table.label(row.get("thread"))
+ if "Main Thread" in thread:
+ main += weight
+ timestamp = table.number(row.get("time"))
+ if timestamp is not None:
+ seconds[int(timestamp / 1e9)] += weight
+ stack = table.resolve(row.get("stack"))
+ backtrace = table.resolve(stack.find("backtrace")) if stack is not None else None
+ if backtrace is None:
+ missing += weight
+ continue
+ frames = [table.resolve(f) for f in backtrace]
+ if not frames:
+ missing += weight
+ continue
+ names = {f.get("name", "Unknown") for f in frames}
+ first = frames[0]
+ leaf[first.get("name", "Unknown")] += weight
+ for name in names:
+ inclusive[name] += weight
+ binary = table.resolve(first.find("binary"))
+ binaries[binary.get("name", "Unknown") if binary is not None else "Unknown"] += weight
+ app_frames = []
+ for frame in frames:
+ binary = table.resolve(frame.find("binary"))
+ if binary is not None and ".app/Contents/MacOS/" in binary.get("path", ""):
+ app_frames.append(frame.get("name", ""))
+ if app_frames:
+ app_weight += weight
+ if any(n and not n.startswith("0x") and n != "<deduplicated_symbol>" for n in app_frames):
+ app_named += weight
+ return {"sampled_ms": total, "main_ms": main, "missing_stack_ms": missing,
+ "app_stack_ms": app_weight, "app_named_stack_ms": app_named,
+ "leaf": leaf.most_common(18), "inclusive": inclusive.most_common(35),
+ "binaries": binaries.most_common(15), "busiest_seconds": seconds.most_common(8)}
+
+
+def event_summary(table, pid=None):
+ rows = []
+ for row in table.rows():
+ if pid is not None and "process" in row:
+ process = table.resolve(row["process"])
+ if process is None or table.number(process.find("pid")) != pid:
+ continue
+ rows.append({key: table.label(value) for key, value in row.items()
+ if key not in ("backtrace", "process", "thread")})
+ return {"count": len(rows), "events": rows[:100]}
+
+
+def system_summary(table):
+ values = []
+ for row in table.rows():
+ value = table.number(row.get("cpu-total-load"))
+ if value is not None:
+ values.append(value)
+ return {"samples": len(values), "cpu_load_mean": statistics.mean(values) if values else None,
+ "cpu_load_peak": max(values) if values else None}
diff --git a/Scripts/performance/report.html b/Scripts/performance/report.html
new file mode 100644
index 0000000..61e622e
--- /dev/null
+++ b/Scripts/performance/report.html
@@ -0,0 +1,1286 @@
+<!doctype html>
+<html lang="zh-CN">
+ <head>
+ <meta charset="utf-8" />
+ <meta
+ name="viewport"
+ content="width=device-width,initial-scale=1" />
+ <meta
+ name="color-scheme"
+ content="light dark" />
+ <meta
+ http-equiv="Content-Security-Policy"
+ content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; connect-src 'none'; base-uri 'none'; form-action 'none'" />
+ <title>@@TITLE@@</title>
+ <style>
+ @font-face {
+ font-family: 'Report Latin';
+ src: local('MesloLGS NF Regular'), local('MesloLGS-NF-Regular');
+ font-style: normal;
+ font-weight: 400;
+ unicode-range: U+0000-024F, U+1E00-1EFF;
+ }
+
+ @font-face {
+ font-family: 'Report Latin';
+ src: local('MesloLGS NF Bold'), local('MesloLGS-NF-Bold');
+ font-style: normal;
+ font-weight: 700;
+ unicode-range: U+0000-024F, U+1E00-1EFF;
+ }
+
+ @font-face {
+ font-family: 'Report Latin';
+ src: local('MesloLGS NF Italic'), local('MesloLGS-NF-Italic');
+ font-style: italic;
+ font-weight: 400;
+ unicode-range: U+0000-024F, U+1E00-1EFF;
+ }
+
+ @font-face {
+ font-family: 'Report Latin';
+ src: local('MesloLGS NF Bold Italic'), local('MesloLGS-NF-Bold-Italic');
+ font-style: italic;
+ font-weight: 700;
+ unicode-range: U+0000-024F, U+1E00-1EFF;
+ }
+
+ :root {
+ --bg: #f2f4f3;
+ --card: #fff;
+ --ink: #172b31;
+ --muted: #607177;
+ --line: #dfe6e4;
+ --teal: #168c80;
+ --nav: #0e2930;
+ --warn: #a76412;
+ --soft: #e8f4f0;
+ --report-font: 'Report Latin', -apple-system, BlinkMacSystemFont, 'PingFang SC', sans-serif;
+ --mono: var(--report-font);
+ }
+
+ * {
+ box-sizing: border-box;
+ }
+
+ html {
+ scroll-behavior: smooth;
+ scroll-padding-top: 30px;
+ }
+
+ body {
+ margin: 0;
+ background: var(--bg);
+ color: var(--ink);
+ font: 15px/1.75 var(--report-font);
+ }
+
+ body.dark {
+ --bg: #122128;
+ --card: #1a2b32;
+ --ink: #e5eeeb;
+ --muted: #a8baba;
+ --line: #31434a;
+ --soft: #203c3a;
+ --warn: #f0b45f;
+ }
+
+ a {
+ color: var(--teal);
+ text-decoration: none;
+ }
+
+ a:hover {
+ text-decoration: underline;
+ }
+
+ button {
+ font: inherit;
+ cursor: pointer;
+ }
+
+ button:focus-visible,
+ a:focus-visible,
+ summary:focus-visible {
+ outline: 3px solid #cc9a45;
+ outline-offset: 4px;
+ }
+
+ .shell {
+ display: grid;
+ grid-template-columns: 228px minmax(0, 1fr);
+ max-width: 1800px;
+ margin: auto;
+ }
+
+ .sidebar {
+ background: var(--nav);
+ color: #b6cbcc;
+ padding: 40px 25px;
+ position: sticky;
+ top: 0;
+ height: 100vh;
+ }
+
+ .brand {
+ font-size: 12px;
+ letter-spacing: 0.2em;
+ color: #e4c180;
+ font-weight: 700;
+ }
+
+ .sidebar strong {
+ display: block;
+ font-size: 24px;
+ color: white;
+ margin: 10px 0 36px;
+ }
+
+ .sidebar nav a {
+ display: block;
+ color: #b6cbcc;
+ padding: 9px 0;
+ font-size: 13px;
+ }
+
+ .sidebar nav span {
+ display: inline-block;
+ width: 28px;
+ color: #709292;
+ font-family: var(--mono);
+ }
+
+ .side-note {
+ border-top: 1px solid #365158;
+ margin-top: 45px;
+ padding-top: 22px;
+ font-size: 12px;
+ }
+
+ .main {
+ padding: 46px 5vw 64px;
+ min-width: 0;
+ }
+
+ .topline {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 15px;
+ flex-wrap: wrap;
+ }
+
+ .eyebrow {
+ font-size: 11px;
+ letter-spacing: 0.13em;
+ font-weight: 700;
+ text-transform: uppercase;
+ color: var(--teal);
+ }
+
+ .actions {
+ display: flex;
+ gap: 8px;
+ }
+
+ .actions button {
+ border: 1px solid var(--line);
+ border-radius: 7px;
+ background: var(--card);
+ color: var(--ink);
+ padding: 6px 12px;
+ font-size: 12px;
+ }
+
+ h1 {
+ font-size: clamp(32px, 4vw, 54px);
+ line-height: 1.18;
+ letter-spacing: -0.045em;
+ margin: 23px 0 14px;
+ }
+
+ h2 {
+ font-size: 25px;
+ margin: 0;
+ letter-spacing: -0.025em;
+ }
+
+ h3 {
+ font-size: 18px;
+ line-height: 1.5;
+ margin: 7px 0 10px;
+ }
+
+ h4 {
+ font-size: 14px;
+ margin: 23px 0 12px;
+ }
+
+ p {
+ margin: 10px 0 17px;
+ }
+
+ .lead {
+ font-size: 16px;
+ color: var(--muted);
+ max-width: 740px;
+ }
+
+ .meta {
+ display: flex;
+ gap: 12px;
+ align-items: center;
+ flex-wrap: wrap;
+ font-size: 12px;
+ color: var(--muted);
+ margin: 23px 0 28px;
+ }
+
+ .badge {
+ display: inline-flex;
+ align-items: center;
+ border-radius: 30px;
+ padding: 4px 11px;
+ font-size: 11px;
+ white-space: nowrap;
+ }
+
+ .badge.ok {
+ background: var(--soft);
+ color: var(--teal);
+ }
+
+ .badge.warn {
+ background: #f4e7d5;
+ color: #976022;
+ }
+
+ .hero-rule {
+ height: 2px;
+ background: linear-gradient(90deg, var(--teal) 0 22%, var(--line) 22% 100%);
+ margin: 22px 0 30px;
+ }
+
+ .kpis {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ gap: 13px;
+ }
+
+ .kpi {
+ background: var(--card);
+ border: 1px solid var(--line);
+ padding: 21px;
+ border-radius: 10px;
+ }
+
+ .kpi .value {
+ font-family: var(--mono);
+ font-size: 34px;
+ letter-spacing: -0.06em;
+ margin: 11px 0 4px;
+ }
+
+ .kpi small {
+ font-size: 12px;
+ line-height: 1.5;
+ color: var(--muted);
+ }
+
+ .kpi .unit {
+ font: 12px var(--mono);
+ color: var(--muted);
+ margin-left: 6px;
+ }
+
+ .kpi .label {
+ font-size: 12px;
+ font-weight: 600;
+ }
+
+ .section {
+ margin-top: 48px;
+ }
+
+ .section-head {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 20px;
+ margin-bottom: 20px;
+ }
+
+ .section-index {
+ font: 12px var(--mono);
+ color: var(--muted);
+ margin-bottom: 6px;
+ }
+
+ .muted {
+ color: var(--muted);
+ font-size: 13px;
+ }
+
+ .panel,
+ .phase {
+ background: var(--card);
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ padding: 25px;
+ }
+
+ .phase {
+ margin-bottom: 22px;
+ }
+
+ .phase .section-head {
+ margin-bottom: 4px;
+ }
+
+ .table-scroll {
+ overflow-x: auto;
+ border: 1px solid var(--line);
+ border-radius: 8px;
+ background: var(--card);
+ }
+
+ table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 12px;
+ text-align: left;
+ }
+
+ th {
+ font-weight: 600;
+ color: var(--muted);
+ background: var(--bg);
+ padding: 12px 14px;
+ white-space: nowrap;
+ }
+
+ td {
+ padding: 12px 14px;
+ border-top: 1px solid var(--line);
+ vertical-align: top;
+ overflow-wrap: anywhere;
+ }
+
+ td:first-child {
+ font-weight: 550;
+ }
+
+ tr:hover td {
+ background: var(--soft);
+ }
+
+ .notice {
+ padding: 17px 20px;
+ border-left: 3px solid var(--teal);
+ background: var(--soft);
+ font-size: 13px;
+ margin: 18px 0;
+ }
+
+ .notice.warn {
+ border-left-color: var(--warn);
+ }
+
+ .two {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 18px;
+ }
+
+ .panel p {
+ font-size: 13px;
+ }
+
+ svg {
+ width: 100%;
+ height: auto;
+ display: block;
+ overflow: visible;
+ }
+
+ svg text {
+ font: 11px var(--mono);
+ fill: var(--muted);
+ }
+
+ svg .grid {
+ stroke: var(--line);
+ stroke-width: 1;
+ }
+
+ details {
+ border-top: 1px solid var(--line);
+ padding: 14px 0;
+ margin-top: 15px;
+ }
+
+ summary {
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ }
+
+ details p {
+ font-size: 12px;
+ color: var(--muted);
+ }
+
+ .empty {
+ padding: 40px;
+ color: var(--muted);
+ text-align: center;
+ }
+
+ .footer {
+ margin-top: 48px;
+ border-top: 1px solid var(--line);
+ padding-top: 20px;
+ display: flex;
+ justify-content: space-between;
+ gap: 20px;
+ color: var(--muted);
+ font-size: 11px;
+ }
+
+ @media (min-width: 1450px) {
+ .main {
+ padding-left: 70px;
+ padding-right: 70px;
+ }
+ }
+
+ @media (max-width: 1100px) {
+ .shell {
+ grid-template-columns: 180px minmax(0, 1fr);
+ }
+
+ .sidebar {
+ padding: 30px 18px;
+ }
+
+ .main {
+ padding: 32px 28px;
+ }
+
+ .kpi {
+ padding: 16px;
+ }
+
+ .kpi .value {
+ font-size: 27px;
+ }
+ }
+
+ @media (max-width: 800px) {
+ .shell {
+ display: block;
+ }
+
+ .sidebar {
+ display: none;
+ }
+
+ .main {
+ padding: 25px 18px;
+ }
+
+ .kpis {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+
+ .two {
+ grid-template-columns: 1fr;
+ }
+
+ .phase,
+ .panel {
+ padding: 19px;
+ }
+
+ .section {
+ margin-top: 34px;
+ }
+
+ .actions button {
+ padding: 5px 9px;
+ }
+
+ .section-head {
+ gap: 10px;
+ }
+
+ .footer {
+ display: block;
+ }
+
+ h1 {
+ font-size: 38px;
+ }
+ }
+
+ @media print {
+ body,
+ body.dark {
+ --bg: #fff;
+ --card: #fff;
+ --ink: #111;
+ --muted: #555;
+ --line: #ddd;
+ --soft: #f4f8f6;
+ background: white;
+ color: #111;
+ font-size: 11px;
+ }
+
+ .sidebar,
+ .actions {
+ display: none !important;
+ }
+
+ .shell {
+ display: block;
+ }
+
+ .main {
+ padding: 0;
+ }
+
+ .section {
+ margin-top: 24px;
+ }
+
+ .phase,
+ .panel {
+ break-inside: avoid;
+ }
+
+ .kpi {
+ padding: 12px;
+ }
+
+ .kpi .value {
+ font-size: 24px;
+ }
+
+ .table-scroll {
+ overflow: visible;
+ }
+
+ th,
+ td {
+ padding: 8px;
+ }
+
+ svg {
+ max-height: 220px;
+ }
+
+ .footer {
+ margin-top: 20px;
+ }
+
+ h1 {
+ font-size: 34px;
+ }
+
+ a {
+ color: inherit;
+ }
+
+ details {
+ break-inside: auto;
+ }
+ }
+
+ .bar-chart {
+ margin-top: 16px;
+ }
+
+ .bar-group {
+ margin: 0 0 16px;
+ }
+
+ .bar-label {
+ font: 12px/1.5 var(--mono);
+ overflow-wrap: anywhere;
+ margin-bottom: 6px;
+ color: var(--ink);
+ }
+
+ .bar-entry {
+ display: grid;
+ grid-template-columns: 48px minmax(30px, 1fr) 104px;
+ gap: 8px;
+ align-items: center;
+ margin: 5px 0;
+ }
+
+ .bar-series {
+ font-size: 11px;
+ color: var(--muted);
+ }
+
+ .bar-track {
+ height: 10px;
+ background: var(--bg);
+ position: relative;
+ border-radius: 3px;
+ overflow: hidden;
+ }
+
+ .bar-track i {
+ position: absolute;
+ top: 0;
+ height: 100%;
+ border-radius: 2px;
+ min-width: 0;
+ }
+
+ .bar-track.missing {
+ background: repeating-linear-gradient(90deg, var(--line) 0 4px, transparent 4px 8px);
+ height: 2px;
+ }
+
+ .zero {
+ position: absolute;
+ top: 0;
+ height: 100%;
+ width: 1px;
+ background: var(--muted);
+ opacity: 0.5;
+ }
+
+ .bar-value {
+ font: 11px var(--mono);
+ text-align: right;
+ white-space: nowrap;
+ color: var(--ink);
+ }
+
+ .bar-value small {
+ font-size: 10px;
+ color: var(--muted);
+ }
+
+ .hotspot {
+ margin-top: 18px;
+ }
+
+ .hotspot > .two {
+ margin-top: 22px;
+ }
+
+ .hotspot .panel {
+ padding: 16px;
+ border: 0;
+ background: var(--bg);
+ }
+
+ .hotspot .bar-track {
+ background: var(--line);
+ }
+
+ .metric-strip {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ gap: 12px;
+ padding-top: 20px;
+ border-top: 1px solid var(--line);
+ }
+
+ .metric-strip span {
+ display: block;
+ color: var(--muted);
+ font-size: 11px;
+ }
+
+ .metric-strip b {
+ font: 18px var(--mono);
+ }
+
+ .thermal-phase {
+ display: grid;
+ grid-template-columns: 64px 1fr;
+ gap: 10px;
+ align-items: center;
+ margin-top: 14px;
+ font: 12px var(--mono);
+ }
+
+ .thermal-state {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 10px;
+ border-radius: 5px;
+ padding: 9px 12px;
+ grid-column: 2;
+ }
+
+ .thermal-phase > b + .thermal-state {
+ grid-column: auto;
+ }
+
+ .thermal-state span {
+ font-size: 10px;
+ }
+
+ .thermal-state.nominal {
+ background: var(--soft);
+ color: var(--teal);
+ }
+
+ .thermal-state.elevated {
+ background: #f4e7d5;
+ color: #976022;
+ }
+
+ .section > .two {
+ margin-top: 18px;
+ }
+
+ .two > .panel {
+ min-width: 0;
+ }
+
+ .hotspot summary {
+ font-size: 15px;
+ }
+
+ details.panel {
+ padding: 20px 25px;
+ }
+
+ @media (max-width: 800px) {
+ .bar-entry {
+ grid-template-columns: 40px minmax(25px, 1fr) 90px;
+ }
+
+ .metric-strip {
+ grid-template-columns: repeat(2, 1fr);
+ }
+
+ .thermal-state {
+ flex-wrap: wrap;
+ }
+
+ .section-head {
+ align-items: flex-start;
+ flex-direction: column;
+ }
+
+ .hotspot .panel {
+ padding: 12px;
+ }
+
+ .hotspot {
+ padding: 16px !important;
+ }
+ }
+
+ @media print {
+ .phase {
+ break-inside: auto;
+ }
+
+ .bar-group,
+ .metric-strip,
+ .thermal-phase {
+ break-inside: avoid;
+ }
+
+ .bar-track,
+ .bar-track i,
+ .thermal-state,
+ svg {
+ -webkit-print-color-adjust: exact;
+ print-color-adjust: exact;
+ }
+
+ .bar-label {
+ font-size: 10px;
+ }
+
+ .bar-group {
+ margin-bottom: 10px;
+ }
+ }
+
+ .trend-chart {
+ margin: 22px 0 28px;
+ padding-top: 15px;
+ border-top: 1px solid var(--line);
+ }
+
+ .trend-stats {
+ display: flex;
+ justify-content: space-between;
+ gap: 12px;
+ flex-wrap: wrap;
+ }
+
+ .trend-stats b {
+ font-size: 14px;
+ }
+
+ .trend-stats span {
+ font-size: 12px;
+ color: var(--muted);
+ }
+
+ .trend-chart svg {
+ touch-action: pan-y;
+ }
+
+ .cursor {
+ stroke: var(--ink);
+ stroke-width: 1;
+ stroke-dasharray: 4 4;
+ pointer-events: none;
+ }
+
+ .cursor[hidden] {
+ display: none;
+ }
+
+ .chart-control {
+ display: none;
+ align-items: center;
+ gap: 18px;
+ padding: 0 3% 0 7%;
+ }
+
+ .js .chart-control {
+ display: flex;
+ }
+
+ .chart-control input {
+ width: 45%;
+ accent-color: var(--teal);
+ cursor: ew-resize;
+ }
+
+ .chart-control output {
+ font: 12px var(--mono);
+ color: var(--ink);
+ }
+
+ .share-track {
+ display: flex;
+ height: 30px;
+ border-radius: 6px;
+ overflow: hidden;
+ margin: 30px 0 20px;
+ }
+
+ .share-track i {
+ display: block;
+ height: 100%;
+ }
+
+ .share-values {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 25px;
+ }
+
+ .share-values span,
+ .share-values small {
+ display: block;
+ font-size: 12px;
+ color: var(--muted);
+ }
+
+ .share-values b {
+ font: 28px/1.8 var(--mono);
+ }
+
+ .share-values > div {
+ border-top: 3px solid #168c80;
+ padding-top: 10px;
+ }
+
+ .share-values > div + div {
+ border-color: #5668cb;
+ }
+
+ .interval-axis {
+ display: flex;
+ justify-content: space-between;
+ color: var(--muted);
+ font: 11px var(--mono);
+ margin: 20px 0 10px;
+ }
+
+ .interval-row {
+ padding: 12px 0;
+ border-bottom: 1px solid var(--line);
+ }
+
+ .interval-row > b {
+ font: 12px var(--mono);
+ }
+
+ .interval-track {
+ position: relative;
+ height: 24px;
+ margin: 8px 6px;
+ background: linear-gradient(var(--line), var(--line)) center/100% 1px no-repeat;
+ }
+
+ .interval-line {
+ position: absolute;
+ top: 10px;
+ height: 4px;
+ background: #168c80;
+ opacity: 0.55;
+ }
+
+ .interval-point {
+ position: absolute;
+ top: 6px;
+ transform: translateX(-50%);
+ width: 12px;
+ height: 12px;
+ background: #168c80;
+ border: 2px solid #168c80;
+ border-radius: 50%;
+ }
+
+ .interval-point.bound {
+ width: 2px;
+ border: 0;
+ border-radius: 0;
+ top: 5px;
+ height: 14px;
+ }
+
+ .interval-point.head {
+ background: var(--card);
+ }
+
+ .interval-point.tail {
+ background: #5668cb;
+ border-color: #5668cb;
+ }
+
+ .interval-values,
+ .interval-key {
+ font: 11px/1.8 var(--mono);
+ color: var(--muted);
+ display: block;
+ }
+
+ .interval-key {
+ margin-top: 15px;
+ }
+
+ .bar-track {
+ height: 16px;
+ border-radius: 2px;
+ }
+
+ .bar-entry {
+ grid-template-columns: 48px minmax(30px, 1fr) 110px;
+ }
+
+ .bar-series:empty {
+ display: none;
+ }
+
+ .bar-entry:has(.bar-series:empty) {
+ grid-template-columns: minmax(30px, 1fr) 110px;
+ }
+
+ .bar-label {
+ line-height: 1.65;
+ }
+
+ .hotspot > .two {
+ grid-template-columns: 1fr;
+ }
+
+ .hotspot .bar-group {
+ margin-bottom: 18px;
+ }
+
+ .hotspot .bar-entry {
+ max-width: 100%;
+ }
+
+ @media (max-width: 800px) {
+ .trend-stats {
+ display: block;
+ }
+
+ .trend-stats span {
+ display: block;
+ margin-top: 5px;
+ }
+
+ .chart-control {
+ padding: 0;
+ gap: 8px;
+ }
+
+ .chart-control output {
+ font-size: 10px;
+ }
+
+ .trend-chart svg text {
+ font-size: 16px;
+ }
+
+ .interval-values {
+ font-size: 10px;
+ }
+
+ .share-values b {
+ font-size: 24px;
+ }
+ }
+
+ @media print {
+ .chart-control {
+ display: none !important;
+ }
+
+ .trend-chart {
+ break-inside: avoid;
+ }
+
+ .share-track,
+ .share-values,
+ .interval-track,
+ .interval-point {
+ -webkit-print-color-adjust: exact;
+ print-color-adjust: exact;
+ }
+ }
+ </style>
+ </head>
+ <body>
+ <div class="shell">
+ <aside class="sidebar">
+ <div class="brand">PERFORMANCE LAB</div>
+ <strong>@@APP@@</strong>
+ <nav aria-label="报告目录">
+ <a href="#overview"><span>01</span>数据总览</a>
+ <a href="#comparison"><span>02</span>阶段对比</a>
+ <a href="#io"><span>03</span>唤醒与磁盘</a>
+ <a href="#measurements"><span>04</span>运行曲线</a>
+ <a href="#hotspots"><span>05</span>CPU 热点</a>
+ <a href="#events"><span>06</span>事件与热状态</a>
+ <a href="#environment"><span>07</span>采集记录</a>
+ </nav>
+ <div class="side-note">@@PRESET@@<br />@@VERSION@@<br />Instruments</div>
+ </aside>
+ <main class="main">
+ <header id="overview">
+ <div class="topline">
+ <span class="eyebrow">Runtime performance / @@PRESET@@</span>
+ <div class="actions">
+ <button
+ id="theme"
+ type="button"
+ aria-label="切换深浅主题">
+ 切换主题
+ </button>
+ <button
+ id="download"
+ type="button">
+ 导出 JSON
+ </button>
+ <button
+ id="print"
+ type="button">
+ 打印报告
+ </button>
+ </div>
+ </div>
+ <h1>@@APP@@<br />性能数据报告</h1>
+ <div class="meta">
+ <span class="badge @@STATE_TONE@@">@@STATE@@</span><span>版本 @@VERSION@@</span><span>有效阶段 @@VALID@@ / @@PLANNED@@</span><span>@@STARTED@@</span>
+ </div>
+ <div class="hero-rule"></div>
+ <div class="kpis">
+ <div class="kpi">
+ <div class="label">记录时间</div>
+ <div class="value">@@MINUTES@@<span class="unit">min</span></div>
+ <small>各阶段累计</small>
+ </div>
+ <div class="kpi">
+ <div class="label">平均 CPU</div>
+ <div class="value">@@CPU@@<span class="unit">%</span></div>
+ <small>按观测时长加权</small>
+ </div>
+ <div class="kpi">
+ <div class="label">footprint 峰值</div>
+ <div class="value">@@MEMORY@@<span class="unit">MiB</span></div>
+ <small>有效阶段最大值</small>
+ </div>
+ <div class="kpi">
+ <div class="label">Hangs 记录</div>
+ <div class="value">@@HANGS@@<span class="unit">条</span></div>
+ <small>采集阶段数:@@HANG_PHASES@@</small>
+ </div>
+ </div>
+ @@ERRORS@@
+ </header>
+ <section
+ id="comparison"
+ class="section">
+ <div class="section-head">
+ <div>
+ <div class="section-index">02 / COMPARISON</div>
+ <h2>阶段对比</h2>
+ </div>
+ <span class="muted">CPU 100% = 1 个逻辑核心</span>
+ </div>
+ <div class="two">@@COMPARISONS@@</div>
+ </section>
+ <section
+ id="io"
+ class="section">
+ <div class="section-head">
+ <div>
+ <div class="section-index">03 / RESOURCES</div>
+ <h2>唤醒、磁盘与系统负载</h2>
+ </div>
+ </div>
+ <div class="two">@@IO_CHARTS@@</div>
+ </section>
+ <section
+ id="measurements"
+ class="section">
+ <div class="section-head">
+ <div>
+ <div class="section-index">04 / TIME SERIES</div>
+ <h2>运行曲线</h2>
+ </div>
+ <span class="muted">横轴:阶段内秒数 · 同一指标各阶段使用相同纵轴</span>
+ </div>
+ @@PHASES@@
+ </section>
+ <section
+ id="hotspots"
+ class="section">
+ <div class="section-head">
+ <div>
+ <div class="section-index">05 / CPU PROFILE</div>
+ <h2>CPU 采样分布与热点</h2>
+ </div>
+ <span class="muted">采样权重 / ms</span>
+ </div>
+ <div class="two">@@HOT_OVERVIEW@@</div>
+ @@HOTSPOTS@@
+ </section>
+ <section
+ id="events"
+ class="section">
+ <div class="section-head">
+ <div>
+ <div class="section-index">06 / EVENTS</div>
+ <h2>事件与热状态</h2>
+ </div>
+ </div>
+ <div class="two">@@EVENTS@@</div>
+ @@EVENT_DETAILS@@
+ </section>
+ @@OPTIONAL@@
+ <section
+ id="environment"
+ class="section">
+ <div class="section-head">
+ <div>
+ <div class="section-index">07 / RECORDS</div>
+ <h2>采集记录</h2>
+ </div>
+ </div>
+ @@RECORDS@@
+ <div class="two section">
+ <article class="panel">
+ <h3>运行环境</h3>
+ @@METADATA@@
+ </article>
+ <article class="panel">
+ <h3>系统 Load Average</h3>
+ @@LOAD@@
+ </article>
+ </div>
+ <details>
+ <summary>App 标识</summary>
+ @@FINGERPRINT@@
+ </details>
+ </section>
+ <footer class="footer"><span>@@APP@@ · Instruments</span><span>@@STARTED@@ — @@ENDED@@</span></footer>
+ </main>
+ </div>
+ <script
+ id="report-data"
+ type="application/json">
+ @@PAYLOAD@@
+ </script>
+ <script>
+ const data = JSON.parse(document.getElementById('report-data').textContent);
+ document.documentElement.classList.add('js');
+ document.querySelectorAll('.trend-chart').forEach((chart) => {
+ const points = data.phases[Number(chart.dataset.phase)].resources.series,
+ key = chart.dataset.key,
+ unit = chart.dataset.unit;
+ const svg = chart.querySelector('svg'),
+ input = chart.querySelector('input');
+ const output = chart.querySelector('output'),
+ cursor = chart.querySelector('.cursor');
+ const start = points[0].t,
+ end = points[points.length - 1].t;
+
+ function select(index) {
+ const t = points[index].t,
+ value = points[index][key] ?? null,
+ x = 68 + ((t - start) / Math.max(end - start, 1)) * 864;
+ cursor.removeAttribute('hidden');
+ cursor.setAttribute('x1', x);
+ cursor.setAttribute('x2', x);
+ output.textContent = `${t.toFixed(2)} s · ${value === null ? 'N/A' : value.toFixed(2) + ' ' + unit}`;
+ input.value = index;
+ input.setAttribute('aria-valuetext', output.textContent);
+ }
+
+ input.addEventListener('input', () => select(Number(input.value)));
+ svg.addEventListener('pointermove', (event) => {
+ const rect = svg.getBoundingClientRect();
+ const time = start + Math.max(0, Math.min(1, (((event.clientX - rect.left) / rect.width) * 960 - 68) / 864)) * (end - start);
+ let index = 0;
+ for (let i = 1; i < points.length; i++) if (Math.abs(points[i].t - time) < Math.abs(points[index].t - time)) index = i;
+ select(index);
+ });
+ select(0);
+ });
+ document.getElementById('theme').addEventListener('click', () => document.body.classList.toggle('dark'));
+ document.getElementById('download').addEventListener('click', () => {
+ const url = URL.createObjectURL(new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }));
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = 'performance-summary.json';
+ link.click();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+ });
+ document.getElementById('print').addEventListener('click', () => window.print());
+ let openedForPrint = [];
+ window.addEventListener('beforeprint', () => {
+ openedForPrint = [...document.querySelectorAll('details:not([open])')];
+ openedForPrint.forEach((element) => (element.open = true));
+ });
+ window.addEventListener('afterprint', () => {
+ openedForPrint.forEach((element) => (element.open = false));
+ openedForPrint = [];
+ });
+ </script>
+ </body>
+</html>
diff --git a/Scripts/performance/report.py b/Scripts/performance/report.py
new file mode 100644
index 0000000..31e0379
--- /dev/null
+++ b/Scripts/performance/report.py
@@ -0,0 +1,309 @@
+"""Render a self-contained report with no remote resources or runtime dependencies"""
+
+import html
+import json
+import math
+from pathlib import Path
+
+
+def escape(value):
+ return html.escape(str(value))
+
+
+def number(value, digits=2, suffix=""):
+ return "N/A" if value is None else f"{value:,.{digits}f}{suffix}"
+
+
+def table(headers, rows):
+ head = "".join(f"<th>{escape(h)}</th>" for h in headers)
+ body = "".join("<tr>" + "".join(f"<td>{escape(c)}</td>" for c in row) + "</tr>" for row in rows)
+ if not body:
+ body = f'<tr><td colspan="{len(headers)}" class="muted">无可用数据</td></tr>'
+ return f'<div class="table-scroll"><table><thead><tr>{head}</tr></thead><tbody>{body}</tbody></table></div>'
+
+
+def chart(series, key, label, color, unit, phase_index, ceiling=None, step=False):
+ width, height, left, right, top, bottom = 960, 250, 68, 28, 32, 40
+ points = [p for p in series if p.get(key) is not None]
+ if not points:
+ return '<div class="empty">无可用采样数据</div>'
+ start, end = min(p["t"] for p in series), max(p["t"] for p in series)
+ peak = max(points, key=lambda p: p[key])
+ maximum = ceiling or nice_max(peak[key])
+ x = lambda t: left + (t - start) / max(end - start, 1) * (width - left - right)
+ y = lambda v: top + (1 - v / maximum) * (height - top - bottom)
+ parts = [f'<div class="trend-chart" data-phase="{phase_index}" data-key="{escape(key)}" data-unit="{escape(unit)}">',
+ f'<div class="trend-stats"><b>{escape(label)}</b><span>最低 {number(min(p[key] for p in points))} · 峰值 {number(peak[key])} {escape(unit)}</span></div>',
+ f'<svg viewBox="0 0 {width} {height}" role="img" aria-label="{escape(label)} 趋势, 单位 {escape(unit)}">']
+ for index in range(5):
+ value = maximum * index / 4
+ yy = y(value)
+ parts.append(f'<line class="grid" x1="{left}" x2="{width - right}" y1="{yy:.2f}" y2="{yy:.2f}"/>')
+ parts.append(f'<text x="{left - 10}" y="{yy + 4:.2f}" text-anchor="end">{value:g}</text>')
+ for index in range(6):
+ t = start + (end - start) * index / 5
+ parts.append(f'<text x="{x(t):.2f}" y="{height - 10}" text-anchor="middle">{t:.0f}s</text>')
+ segments, current = [], []
+ previous = None
+ for point in series:
+ if point.get(key) is None or (previous is not None and point["t"] - previous > 5):
+ if current:
+ segments.append(current)
+ current = []
+ if point.get(key) is not None:
+ current.append(point)
+ previous = point["t"]
+ if current:
+ segments.append(current)
+ for segment in segments:
+ path = f'M {x(segment[0]["t"]):.2f} {y(segment[0][key]):.2f}'
+ for point in segment[1:]:
+ path += (f' H {x(point["t"]):.2f} V {y(point[key]):.2f}' if step else
+ f' L {x(point["t"]):.2f} {y(point[key]):.2f}')
+ parts.append(f'<path d="{path} L {x(segment[-1]["t"]):.2f} {y(0):.2f} L {x(segment[0]["t"]):.2f} {y(0):.2f} Z" fill="{color}" opacity=".10"/>')
+ parts.append(f'<path d="{path}" fill="none" stroke="{color}" stroke-width="2"/>')
+ if len(segment) == 1:
+ parts.append(f'<circle cx="{x(segment[0]["t"]):.2f}" cy="{y(segment[0][key]):.2f}" r="3" fill="{color}"/>')
+ anchor = "end" if x(peak["t"]) > width / 2 else "start"
+ parts.append(f'<circle cx="{x(peak["t"]):.2f}" cy="{y(peak[key]):.2f}" r="4" fill="{color}"/>')
+ parts.append(f'<text x="{x(peak["t"]):.2f}" y="{y(peak[key]) - 10:.2f}" text-anchor="{anchor}">峰值 {peak[key]:.2f}</text>')
+ parts.append(f'<line class="cursor" x1="{left}" x2="{left}" y1="{top}" y2="{height - bottom}" hidden/></svg>')
+ parts.append(f'<div class="chart-control"><input type="range" min="0" max="{len(series) - 1}" value="0" aria-label="{escape(label)} 采样时间"><output aria-live="polite"></output></div></div>')
+ return "".join(parts)
+
+
+def nice_max(value):
+ if value <= 0:
+ return 1
+ magnitude = 10 ** math.floor(math.log10(value))
+ step = magnitude / 2
+ return math.ceil(value * 1.1 / step) * step
+
+
+COLORS = ["#168c80", "#5668cb", "#bd812e", "#c96675"]
+
+
+def bars(groups, unit="", digits=2):
+ values = [value for _, entries in groups for _, value, _ in entries if value is not None]
+ low, high = min([0] + values), max([0] + values)
+ extent = high - low or 1
+ zero = -low / extent * 100
+ parts = [f'<div class="bar-chart" role="img" aria-label="{escape(unit)} 柱状图">']
+ for label, entries in groups:
+ parts.append(f'<div class="bar-group"><div class="bar-label">{escape(label)}</div>')
+ for name, value, color in entries:
+ parts.append(f'<div class="bar-entry"><span class="bar-series">{escape(name)}</span>')
+ if value is None:
+ parts.append('<div class="bar-track missing"></div><b class="bar-value">N/A</b>')
+ else:
+ position = (min(0, value) - low) / extent * 100
+ width = abs(value) / extent * 100
+ parts.append(f'<div class="bar-track"><span class="zero" style="left:{zero:.4f}%"></span><i style="left:{position:.4f}%;width:{width:.4f}%;background:{color}" data-value="{value}"></i></div><b class="bar-value">{number(value, digits)} <small>{escape(unit)}</small></b>')
+ parts.append('</div>')
+ parts.append('</div>')
+ return ''.join(parts) + ('<div class="empty">无采集数据</div>' if not groups else '') + '</div>'
+
+
+def ranked(items, unit="ms", color=COLORS[0], digits=0):
+ return bars([(label, [("", value, color)]) for label, value in items], unit, digits)
+
+
+def panel(title, content, note=""):
+ return '<article class="panel"><h3>' + escape(title) + '</h3>' + ('<p class="muted">' + escape(note) + '</p>' if note else '') + content + '</article>'
+
+
+def distribution(main, total):
+ if not total:
+ return '<div class="empty">无 CPU 样本</div>'
+ ratio = main / total * 100
+ return f'''<div class="share-chart"><div class="share-track" role="img" aria-label="主线程 {ratio:.1f}%, 其他线程 {100 - ratio:.1f}%"><i style="width:{ratio:.4f}%;background:{COLORS[0]}"></i><i style="width:{100 - ratio:.4f}%;background:{COLORS[1]}"></i></div>
+<div class="share-values"><div><span>主线程</span><b>{ratio:.1f}%</b><small>{main:,.0f} ms</small></div><div><span>其他线程</span><b>{100 - ratio:.1f}%</b><small>{total - main:,.0f} ms</small></div></div></div>'''
+
+
+def interval_chart(rows, paired=False):
+ values = [v for _, entries in rows for v in entries if v is not None]
+ if not values:
+ return '<div class="empty">无可用数据</div>'
+ maximum = nice_max(max(values))
+ x = lambda value: 100 * value / maximum
+ parts = ['<div class="interval-chart">', '<div class="interval-axis"><span>0</span><span>' + number(maximum, 0) + ' MiB</span></div>']
+ for label, values in rows:
+ parts.append(f'<div class="interval-row"><b>{escape(label)}</b>')
+ if any(v is None for v in values):
+ parts.append('<span class="muted">N/A</span></div>')
+ continue
+ first, last = values[0], values[-1]
+ description = (f'首段 {first:.1f} → 尾段 {last:.1f} MiB · 变化 {last - first:+.1f} MiB' if paired else
+ f'最小 {first:.1f} · 中位 {values[1]:.1f} · 峰值 {last:.1f} MiB')
+ parts.append(f'<div class="interval-track" role="img" aria-label="{escape(description)}"><i class="interval-line" style="left:{x(min(first, last)):.4f}%;width:{x(abs(last - first)):.4f}%"></i>')
+ for i, value in enumerate(values):
+ kind = ("head" if i == 0 else "tail") if paired else ("median" if i == 1 else "bound")
+ parts.append(f'<i class="interval-point {kind}" style="left:{x(value):.4f}%" title="{value:.2f} MiB"></i>')
+ parts.append('</div><span class="interval-values">' + description + '</span></div>')
+ parts.append('<div class="interval-key">' + ('○ 首段 ● 尾段' if paired else '┃ 最小值 / 峰值 ● 中位数') + '</div></div>')
+ return ''.join(parts)
+
+
+def write_report(data, destination):
+ import collections
+ import re
+ phases = data.get("phases", [])
+ valid = [p for p in phases if p.get("resources") and not p.get("errors")]
+ target, env = data.get("target", {}), data.get("environment", {})
+ measured = sum(p.get("recorded_s", 0) for p in phases)
+ cpu_phases = [p for p in valid if p["resources"].get("cpu_mean") is not None]
+ span = sum(p["resources"]["span_s"] for p in cpu_phases)
+ cpu_mean = sum(p["resources"]["cpu_mean"] * p["resources"]["span_s"] for p in cpu_phases) / span if span else None
+ footprints = [p["resources"]["footprint"]["max"] for p in valid if p["resources"].get("footprint")]
+ hang_phases = [p for p in valid if "potential-hangs" in p]
+ hangs = sum(p["potential-hangs"]["count"] for p in hang_phases) if hang_phases else None
+ state = {"complete": "采集完成", "incomplete": "采集不完整", "running": "采集中", "interrupted": "采集已中断"}.get(data.get("state"), "状态未知")
+ tone = "ok" if data.get("state") == "complete" else "warn"
+ if data.get("budget_breaches"):
+ state, tone = "超过配置预算", "warn"
+
+ def resource_groups(specification, scale=1):
+ groups = []
+ for phase in valid:
+ r = phase["resources"]
+ entries = []
+ for index, (label, key) in enumerate(specification):
+ value = r.get(key)
+ entries.append((label, value / scale if value is not None else None, COLORS[index]))
+ groups.append((phase["id"], entries))
+ return groups
+
+ comparisons = [panel("平均 CPU", bars(resource_groups([("均值", "cpu_mean")]), "%")),
+ panel("CPU P95 与峰值", bars(resource_groups([("P95", "cpu_p95"), ("峰值", "cpu_peak")]), "%"))]
+ memory_rows = [(p["id"], [(p["resources"].get("footprint") or {}).get(key)
+ for key in ("min", "median", "max")]) for p in valid]
+ comparisons.append(panel("内存 footprint 分布", interval_chart(memory_rows)))
+ trends = [(p["id"], p["resources"]["memory_trend"]) for p in valid if p["resources"].get("memory_trend")]
+ comparisons.append(panel("footprint 首尾变化", interval_chart([(name, [t["head_median"], t["tail_median"]])
+ for name, t in trends], paired=True),
+ "窗口长度为 60 秒与阶段跨度四分之一中的较小值"))
+ comparisons.append(panel("footprint 变化斜率", ranked([(name, t["slope_mib_min"]) for name, t in trends], "MiB/min", digits=2),
+ "按阶段样本作最小二乘拟合"))
+ comparisons.append(panel("footprint 首尾差值", ranked([(name, t["delta_mib"]) for name, t in trends], "MiB", digits=2),
+ "尾段窗口中位数减去首段窗口中位数"))
+ io_charts = [panel("Idle Wake Ups 速率", bars(resource_groups([("均值", "wakeups_per_s")]), "次/s")),
+ panel("磁盘读取与写入", bars(resource_groups([("读取", "read_bytes"), ("写入", "written_bytes")], 1024), "KiB", 1)),
+ panel("磁盘平均吞吐", bars(resource_groups([("读取", "read_bytes_per_s"), ("写入", "written_bytes_per_s")], 1024), "KiB/s")),
+ panel("系统 CPU", bars([(p["id"], [("均值", p["system"].get("cpu_load_mean"), COLORS[0]),
+ ("峰值", p["system"].get("cpu_load_peak"), COLORS[1])])
+ for p in valid if p.get("system")], "%", 1), "各逻辑核心合计")]
+ profiles = [p for p in valid if p.get("profile")]
+ total = sum(p["profile"]["sampled_ms"] for p in profiles)
+ main = sum(p["profile"]["main_ms"] for p in profiles)
+ libraries = collections.Counter()
+ for p in profiles:
+ for name, weight in p["profile"].get("binaries", []):
+ libraries[name] += weight
+ hot_overview = panel("主线程 CPU 样本分布", distribution(main, total)) + panel("叶节点所属库 · 已导出 Top 10", ranked(libraries.most_common(10)))
+ phase_html, hotspot_html, record_rows, event_rows = [], [], [], []
+ ceilings = {key: nice_max(max([point[key] for p in phases for point in p.get("resources", {}).get("series", [])
+ if point.get(key) is not None] or [0]))
+ for key in ("cpu", "footprint", "rss", "compressed", "threads")}
+ for index, phase in enumerate(phases):
+ r = phase.get("resources", {})
+ content = f'<article class="phase" id="phase-{index}"><div class="section-head"><div><span class="eyebrow">{escape(phase["template"])}</span><h3>{escape(phase["id"])}</h3></div><span class="badge {"ok" if phase in valid else "warn"}">{"已采集" if phase in valid else "部分数据"}</span></div>'
+ content += f'<p class="muted">{escape(phase.get("trace_started", phase.get("started", "N/A")))} · {number(phase.get("recorded_s"), 2)} s</p>'
+ if r:
+ content += chart(r["series"], "cpu", "CPU", COLORS[0], "%", index, ceilings["cpu"])
+ for key, label, color in zip(["footprint", "rss", "compressed"], ["Footprint", "RSS", "压缩内存"], COLORS):
+ content += chart(r["series"], key, label, color, "MiB", index, ceilings[key])
+ content += chart(r["series"], "threads", "线程数", COLORS[1], "个", index, ceilings["threads"], step=True)
+ metrics = [("CPU P50", number(r.get("cpu_p50"), 2, "%")), ("CPU P95", number(r.get("cpu_p95"), 2, "%")),
+ ("唤醒次数", number(r.get("wakeups"), 0)), ("资源样本", str(r["samples"]))]
+ content += '<div class="metric-strip">' + ''.join(f'<div><span>{escape(label)}</span><b>{escape(value)}</b></div>' for label, value in metrics) + '</div>'
+ if phase.get("errors"):
+ content += '<div class="notice warn">' + '<br>'.join(escape(e) for e in phase["errors"]) + '</div>'
+ phase_html.append(content + '</article>')
+ profile = phase.get("profile")
+ if profile:
+ hot = f'<details class="panel hotspot" {"open" if index == 0 else ""}><summary>{escape(phase["id"])} · CPU 采样权重 {profile["sampled_ms"]:,.0f} ms</summary>'
+ hot += '<div class="two">' + panel("叶节点热点 · Top 12", ranked(profile["leaf"][:12]))
+ hot += panel("调用链热点 · Top 12", ranked(profile["inclusive"][:12], color=COLORS[1]), "权重包含子调用") + '</div>'
+ hot += '<div class="two">' + panel("高 CPU 采样权重的 1 秒区间", ranked([(f"{t}–{t + 1} s", value) for t, value in profile["busiest_seconds"]]))
+ hot += panel("调用栈采样记录", ranked([("有调用栈", profile["sampled_ms"] - profile["missing_stack_ms"]),
+ ("缺失调用栈", profile["missing_stack_ms"]),
+ ("含 App 帧", profile["app_stack_ms"]),
+ ("含命名 App 帧", profile["app_named_stack_ms"])], color=COLORS[2])) + '</div>'
+ hot += '<details><summary>全部已导出热点</summary>' + table(["叶节点", "权重 / ms"], [(name, number(weight, 0)) for name, weight in profile["leaf"]])
+ hot += table(["调用链", "权重 / ms"], [(name, number(weight, 0)) for name, weight in profile["inclusive"]]) + '</details></details>'
+ hotspot_html.append(hot)
+ record_rows.append([phase["id"], phase["template"], number(phase.get("recorded_s"), 2, " s"),
+ r.get("samples", "N/A"), number(r.get("max_gap_s"), 2, " s"),
+ number(r.get("cpu_coverage") * 100 if r.get("cpu_coverage") is not None else None, 1, "%"),
+ "已采集" if phase in valid else "部分数据"])
+ for key, label in [("potential-hangs", "Hangs"), ("hang-risks", "Hang risks")]:
+ for event in phase.get(key, {}).get("events", []):
+ event_rows.append([phase["id"], label, ' · '.join(f'{k}: {v}' for k, v in event.items())])
+ events_chart = bars([(p["id"], [("Hangs", p.get("potential-hangs", {}).get("count"), COLORS[0]),
+ ("Hang risks", p.get("hang-risks", {}).get("count"), COLORS[2])]) for p in phases], "条", 0)
+ thermal = '<div class="thermal-grid">'
+ for p in phases:
+ events = p.get("device-thermal-state-intervals", {}).get("events", [])
+ thermal += f'<div class="thermal-phase"><b>{escape(p["id"])}</b>'
+ if not events:
+ thermal += '<span class="muted">N/A</span>'
+ for event in events:
+ state_name = event.get("thermal-state", "N/A")
+ thermal += f'<div class="thermal-state {"nominal" if state_name.lower() == "nominal" else "elevated"}"><b>{escape(state_name)}</b><span>{escape(event.get("start", ""))} → {escape(event.get("end", ""))}</span></div>'
+ thermal += '</div>'
+ thermal += '</div>'
+ metadata = [["App", target.get("name", "N/A")], ["Bundle ID", target.get("bundle_id", "N/A")],
+ ["版本 / 构建", f'{target.get("version", "N/A")} / {target.get("build", "N/A")}'],
+ ["主进程 PID", target.get("identity", {}).get("pid", "N/A")],
+ ["macOS / 架构", f'{env.get("os", "N/A")} / {env.get("arch", "N/A")}'],
+ ["芯片 / 逻辑核心", f'{env.get("chip", "N/A")} / {env.get("cores", "N/A")}'],
+ ["内存", number(int(env["memory_bytes"]) / 2 ** 30, 0, " GiB") if env.get("memory_bytes") else "N/A"],
+ ["Instruments", env.get("instruments", "N/A")], ["电源", env.get("power", "N/A")],
+ ["工作负载", data.get("config", {}).get("workload", "N/A")]]
+ fingerprint = [["App 文件指纹", target.get("binary_sha256", "N/A")],
+ ["Mach-O UUID", '; '.join(f'{arch}: {uuid}' for uuid, arch in target.get("uuids", []))]]
+ load_groups = [(label, [("开始", env.get("load_before", [None] * 3)[i], COLORS[0]),
+ ("结束", env.get("load_after", [None] * 3)[i], COLORS[1])])
+ for i, label in enumerate(["1 分钟", "5 分钟", "15 分钟"])]
+ optional = ''
+ comparison = data.get("comparison")
+ if comparison:
+ optional += '<section class="section"><h2>历史基线差值</h2>'
+ if comparison.get("deltas"):
+ optional += '<div class="two">' + panel("平均 CPU 差值", ranked([(r["phase"], r["cpu_pp"]) for r in comparison["deltas"]], "百分点", digits=2))
+ optional += panel("footprint 中位数差值", ranked([(r["phase"], r["footprint_mib"]) for r in comparison["deltas"]], "MiB", digits=2)) + '</div>'
+ else:
+ optional += table(["比较状态", "字段"], [["条件不匹配", ', '.join(comparison.get("differences", []))]])
+ optional += '</section>'
+ budgets = data.get("config", {})
+ if budgets.get("cpu_mean_budget") is not None or budgets.get("footprint_budget") is not None:
+ optional += '<section class="section"><h2>配置预算</h2>' + table(["平均 CPU 上限", "footprint 峰值上限", "超出项"], [[
+ number(budgets.get("cpu_mean_budget"), 2, "%"), number(budgets.get("footprint_budget"), 1, " MiB"), ', '.join(data.get("budget_breaches", [])) or "0"]]) + '</section>'
+ portable = json.loads(json.dumps(data))
+ portable.get("target", {}).get("identity", {}).pop("path", None)
+ for phase in portable.get("phases", []):
+ phase.pop("commands", None)
+ payload = json.dumps(portable, ensure_ascii=False, allow_nan=False).replace("&", "\\u0026").replace("<", "\\u003c").replace(">", "\\u003e")
+ errors = data.get("errors", [])
+ replacements = {"TITLE": escape(target.get("name", "App")) + " · 性能数据", "APP": escape(target.get("name", "App")),
+ "STATE": state, "STATE_TONE": tone, "STARTED": escape(data.get("started", "N/A")),
+ "ENDED": escape(data.get("ended", "采集中")), "PRESET": escape(data.get("config", {}).get("preset", "N/A")),
+ "VERSION": escape(f'{target.get("version", "N/A")} ({target.get("build", "N/A")})'),
+ "MINUTES": number(measured / 60, 1), "CPU": number(cpu_mean, 2),
+ "MEMORY": number(max(footprints) if footprints else None, 1), "HANGS": str(hangs) if hangs is not None else "N/A",
+ "HANG_PHASES": str(len(hang_phases)), "VALID": str(len(valid)), "PLANNED": str(len(data.get("plan", []))),
+ "ERRORS": '<div class="notice warn">' + '<br>'.join(escape(e) for e in errors) + '</div>' if errors else '',
+ "COMPARISONS": ''.join(comparisons), "IO_CHARTS": ''.join(io_charts), "PHASES": ''.join(phase_html),
+ "HOT_OVERVIEW": hot_overview, "HOTSPOTS": ''.join(hotspot_html),
+ "EVENTS": panel("Hangs / Hang risks", events_chart) + panel("热状态", thermal),
+ "EVENT_DETAILS": table(["阶段", "事件", "记录"], event_rows) if event_rows else '',
+ "RECORDS": table(["阶段", "模板", "记录时长", "样本数", "最大间隔", "CPU 计数覆盖", "状态"], record_rows),
+ "METADATA": table(["项目", "值"], metadata), "FINGERPRINT": table(["字段", "值"], fingerprint),
+ "LOAD": bars(load_groups, "", 2), "OPTIONAL": optional, "PAYLOAD": payload}
+ template = Path(__file__).with_name("report.html").read_text()
+ document = re.sub(r"@@([A-Z_]+)@@", lambda match: replacements[match[1]], template)
+ destination = Path(destination)
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ temporary = destination.with_suffix(".html.tmp")
+ temporary.write_text(document)
+ temporary.replace(destination)
diff --git a/Scripts/performance/run.py b/Scripts/performance/run.py
new file mode 100644
index 0000000..acf9a32
--- /dev/null
+++ b/Scripts/performance/run.py
@@ -0,0 +1,412 @@
+#!/usr/bin/env python3
+"""Non-invasive profiling of an already running macOS app, using xctrace"""
+
+import argparse
+import ctypes
+import datetime as dt
+import hashlib
+import json
+import os
+import platform
+import plistlib
+import re
+import signal
+import subprocess
+import sys
+import tempfile
+import time
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+sys.dont_write_bytecode = True
+
+from analyze import Table, event_summary, profile_summary, resource_summary, system_summary
+from report import write_report
+
+VERSION = "1"
+ROOT = Path(__file__).resolve().parents[2]
+SCHEMAS = ("activity-monitor-process-live", "time-profile", "potential-hangs", "hang-risks",
+ "device-thermal-state-intervals", "activity-monitor-system")
+PRESETS = {"quick": (5, 20, 2, 60, 20), "standard": (20, 60, 3, 300, 60),
+ "extended": (30, 120, 3, 900, 120)}
+
+
+def now():
+ return dt.datetime.now().astimezone().isoformat(timespec="seconds")
+
+
+def status(message):
+ print(f"[{now()}] {message}", flush=True)
+
+
+def capture(args, timeout=20):
+ result = subprocess.run(args, capture_output=True, timeout=timeout)
+ if result.returncode:
+ raise RuntimeError(f"{args[0]} exited {result.returncode}: {result.stderr.decode(errors='replace')[-1000:]}")
+ return result.stdout.decode(errors="replace").strip()
+
+
+def optional(args):
+ try:
+ return capture(args)
+ except (OSError, RuntimeError, subprocess.TimeoutExpired):
+ return None
+
+
+def process_path(pid):
+ lib = ctypes.CDLL("/usr/lib/libproc.dylib")
+ lib.proc_pidpath.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32]
+ lib.proc_pidpath.restype = ctypes.c_int
+ buffer = ctypes.create_string_buffer(4096)
+ size = lib.proc_pidpath(pid, buffer, len(buffer))
+ return Path(os.fsdecode(buffer.value)).resolve() if size > 0 else None
+
+
+def identity(pid):
+ path = process_path(pid)
+ started = optional(["/bin/ps", "-p", str(pid), "-o", "lstart="])
+ return {"pid": pid, "path": str(path) if path else None, "started": started}
+
+
+def inspect_target(app, pid):
+ info = plistlib.loads((app / "Contents/Info.plist").read_bytes())
+ executable = (app / "Contents/MacOS" / info["CFBundleExecutable"]).resolve()
+ if not executable.is_file():
+ raise ValueError("App executable does not exist")
+ if pid is None:
+ candidates = [int(p) for p in capture(["/bin/ps", "-A", "-o", "pid="]).split()]
+ matches = [p for p in candidates if process_path(p) == executable]
+ if len(matches) != 1:
+ raise ValueError(f"Expected one running instance of {app.name}, found {len(matches)}; specify --pid")
+ pid = matches[0]
+ original = identity(pid)
+ if original["path"] != str(executable) or not original["started"]:
+ raise ValueError("PID does not match the requested app executable")
+ entitlements = subprocess.run(["/usr/bin/codesign", "-d", "--entitlements", ":-", str(app)],
+ capture_output=True, timeout=20)
+ ent = None
+ for stream in (entitlements.stdout, entitlements.stderr):
+ start = stream.find(b"<?xml")
+ end = stream.find(b"</plist>")
+ if start >= 0 and end >= start:
+ ent = plistlib.loads(stream[start:end + len(b"</plist>")])
+ break
+ uuids = optional(["/usr/bin/xcrun", "dwarfdump", "--uuid", str(executable)])
+ uuid_list = re.findall(r"UUID: ([A-Fa-f0-9-]+) \(([^)]+)\)", uuids or "")
+ with executable.open("rb") as file:
+ binary_hash = hashlib.file_digest(file, "sha256").hexdigest()
+ return {"name": app.stem, "bundle_id": info.get("CFBundleIdentifier"),
+ "version": info.get("CFBundleShortVersionString"), "build": info.get("CFBundleVersion"),
+ "binary_sha256": binary_hash, "uuids": uuid_list,
+ "get_task_allow": bool(ent.get("com.apple.security.get-task-allow")) if ent is not None else None,
+ "identity": original}
+
+
+def load_schemas(developer):
+ base = Path(developer).parent / "Applications/Instruments.app/Contents/Packages"
+ found = {}
+ for path in base.rglob("schemas.xml"):
+ for schema in ET.parse(path).getroot().findall("schema"):
+ if schema.get("name") in SCHEMAS:
+ found[schema.get("name")] = [c.get("mnemonic") for c in schema.findall("column")]
+ if "activity-monitor-process-live" not in found:
+ raise RuntimeError("No Activity Monitor column schema found in the selected Xcode")
+ return found
+
+
+def run_command(args, logfile, timeout, expected=None):
+ began = time.monotonic()
+ interrupted = False
+ failure = None
+ directory = logfile.parent.stat()
+
+ def check_output():
+ try:
+ current = logfile.parent.stat()
+ if (current.st_dev, current.st_ino) == (directory.st_dev, directory.st_ino):
+ return
+ except FileNotFoundError:
+ pass
+ raise RuntimeError(f"Output directory removed or replaced during capture: {logfile.parent}")
+
+ with logfile.open("w") as log:
+ process = subprocess.Popen(args, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
+ try:
+ while process.poll() is None:
+ check_output()
+ elapsed = time.monotonic() - began
+ if elapsed >= timeout:
+ failure = "Command timeout"
+ break
+ if expected and identity(expected["pid"]) != expected:
+ failure = "Target exited or process identity changed"
+ break
+ time.sleep(1)
+ except KeyboardInterrupt:
+ interrupted = True
+ finally:
+ if process.poll() is None:
+ os.killpg(process.pid, signal.SIGINT)
+ try:
+ process.wait(timeout=20)
+ except subprocess.TimeoutExpired:
+ os.killpg(process.pid, signal.SIGKILL)
+ process.wait(timeout=10)
+ check_output()
+ result = {"argv": args, "exit_code": process.returncode,
+ "elapsed_s": round(time.monotonic() - began, 2), "log": logfile.name}
+ if failure:
+ result["error"] = failure
+ if interrupted:
+ raise KeyboardInterrupt
+ return result
+
+
+def save(data, output):
+ temporary = output / "results.json.tmp"
+ temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2, allow_nan=False) + "\n")
+ temporary.replace(output / "results.json")
+ write_report(data, output / "report.html")
+
+
+def analyze_phase(phase, output, schemas, pid):
+ for name, columns in schemas.items():
+ file = output / f"{phase['id']}-{name}.xml"
+ if not file.exists() or name not in phase.get("exported", []):
+ continue
+ try:
+ table = Table(file, columns)
+ if name == "activity-monitor-process-live":
+ phase["resources"] = resource_summary(table, pid)
+ elif name == "time-profile":
+ phase["profile"] = profile_summary(table, pid)
+ elif name == "activity-monitor-system":
+ phase["system"] = system_summary(table)
+ else:
+ phase[name] = event_summary(table, pid if name in ("potential-hangs", "hang-risks") else None)
+ except (ValueError, KeyError, ET.ParseError, TypeError) as error:
+ phase["errors"].append(f"{name}: {error}")
+
+
+def record_phase(phase, data, output, schemas):
+ target = data["target"]["identity"]
+ if identity(target["pid"]) != target:
+ raise RuntimeError("Target process changed before recording")
+ phase.update(started=now(), errors=[], commands=[], exported=[])
+ phase["trace"] = phase["id"] + ".trace"
+ args = ["/usr/bin/xcrun", "xctrace", "record", "--template", phase["template"],
+ "--attach", str(target["pid"]), "--time-limit", f"{phase['seconds']}s",
+ "--output", str(output / phase["trace"]), "--no-prompt"]
+ if phase["template"] == "Time Profiler":
+ args.extend(["--instrument", "Activity Monitor"])
+ command = run_command(args, output / f"{phase['id']}-record.log", phase["seconds"] + 150, target)
+ phase["commands"].append(command)
+ if command["exit_code"] or command.get("error"):
+ phase["errors"].append(command.get("error", "xctrace recording failed; see record log"))
+ elif "[Error]" in (output / command["log"]).read_text(errors="replace"):
+ phase["errors"].append("xctrace reported an error despite a zero exit code")
+ if identity(target["pid"]) != target:
+ phase["errors"].append("Target identity changed during recording")
+ trace = output / phase["trace"]
+ if not trace.exists():
+ phase["errors"].append("No trace artifact was created")
+ return
+ toc = output / f"{phase['id']}-toc.xml"
+ cmd = run_command(["/usr/bin/xcrun", "xctrace", "export", "--input", str(trace),
+ "--toc", "--output", str(toc)], output / f"{phase['id']}-toc.log", 120)
+ phase["commands"].append(cmd)
+ if cmd["exit_code"] or cmd.get("error"):
+ phase["errors"].append("TOC export failed")
+ return
+ root = ET.parse(toc).getroot()
+ phase["recorded_s"] = float(root.findtext(".//summary/duration", "0"))
+ phase["trace_started"] = root.findtext(".//summary/start-date")
+ phase["hang_settings"] = [e.text for e in root.findall(".//instrument[@name='Hangs']//key")]
+ phase["tables"] = [e.get("schema") for e in root.findall(".//data/table")]
+ if phase["recorded_s"] < phase["seconds"] * .9:
+ phase["errors"].append("Recording duration below 90% of requested duration")
+ for name in SCHEMAS:
+ if name not in phase["tables"] or name not in schemas:
+ continue
+ xml = output / f"{phase['id']}-{name}.xml"
+ cmd = run_command(["/usr/bin/xcrun", "xctrace", "export", "--input", str(trace),
+ "--xpath", f'/trace-toc/run[@number="1"]/data/table[@schema="{name}"]',
+ "--output", str(xml)], output / f"{phase['id']}-{name}.log", 120)
+ phase["commands"].append(cmd)
+ if cmd["exit_code"] or cmd.get("error"):
+ phase["errors"].append(f"{name}: export failed")
+ else:
+ phase["exported"].append(name)
+ analyze_phase(phase, output, schemas, target["pid"])
+ if "resources" not in phase:
+ phase["errors"].append("No valid resource measurements")
+ else:
+ resource = phase["resources"]
+ phase["errors"].extend(resource["errors"])
+ if resource["span_s"] < phase["seconds"] * .8:
+ phase["errors"].append("Resource coverage below 80% of requested duration")
+ if resource["max_gap_s"] > 5:
+ phase["errors"].append("Resource sample gap exceeds 5 seconds")
+ if resource["cpu_coverage"] < .95:
+ phase["errors"].append("CPU counter coverage below 95%")
+ if resource.get("footprint") is None:
+ phase["errors"].append("Physical footprint was not available")
+ if phase["template"] == "Time Profiler" and "profile" not in phase:
+ phase["errors"].append("No decoded CPU profile")
+ phase["ended"] = now()
+
+
+def compare(data, path):
+ previous = json.loads(path.read_text())
+ keys = [("target", "bundle_id"), ("environment", "os"), ("environment", "chip"),
+ ("environment", "arch"), ("environment", "cores"), ("environment", "memory_bytes"),
+ ("environment", "power_source"),
+ ("environment", "instruments"), ("config", "workload"), ("config", "preset"),
+ ("config", "cpu_mean_budget"), ("config", "footprint_budget")]
+ differences = [f"{a}.{b}" for a, b in keys if data.get(a, {}).get(b) != previous.get(a, {}).get(b)]
+ if data.get("format_version") != previous.get("format_version"):
+ differences.append("format_version")
+ if previous.get("state") != "complete":
+ differences.append("baseline.state")
+ if data.get("state") != "complete":
+ differences.append("current.state")
+ if [(p["id"], p["seconds"]) for p in data["phases"]] != [(p["id"], p["seconds"]) for p in previous.get("phases", [])]:
+ differences.append("phase_plan")
+ result = {"baseline_version": previous.get("target", {}).get("version"),
+ "compatible": not differences, "differences": differences, "deltas": []}
+ if not differences:
+ for current, old in zip(data["phases"], previous["phases"]):
+ a, b = current.get("resources"), old.get("resources")
+ if a and b and not current.get("errors") and not old.get("errors"):
+ result["deltas"].append({"phase": current["id"], "cpu_pp": a["cpu_mean"] - b["cpu_mean"],
+ "footprint_mib": a["footprint"]["median"] - b["footprint"]["median"]})
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--app", type=Path, default=Path("/Applications/CodexBar.app"))
+ parser.add_argument("--pid", type=int)
+ parser.add_argument("--preset", choices=PRESETS, default="standard")
+ parser.add_argument("--output", type=Path)
+ parser.add_argument("--workload", default="Natural workload; UI and active tasks uncontrolled")
+ parser.add_argument("--baseline", type=Path)
+ parser.add_argument("--cpu-mean-budget", type=float)
+ parser.add_argument("--footprint-budget", type=float, help="Physical footprint budget in MiB")
+ parser.add_argument("--render", type=Path, help="Regenerate HTML from an existing results.json without profiling")
+ args = parser.parse_args()
+ if args.render:
+ data = json.loads(args.render.read_text())
+ destination = args.output or args.render.parent / "report.html"
+ write_report(data, destination)
+ print(destination)
+ return 0
+ for value in (args.cpu_mean_budget, args.footprint_budget):
+ if value is not None and (not 0 < value < float("inf")):
+ parser.error("Budgets must be finite positive numbers")
+ output = (args.output or ROOT / "Build/Performance" / dt.datetime.now().strftime("%Y%m%d-%H%M%S")).resolve()
+ try:
+ output.mkdir(parents=True, exist_ok=False)
+ except OSError as error:
+ parser.error(f"Cannot create a new output directory: {error}")
+ os.chmod(output, 0o700)
+ data = {"format_version": VERSION, "started": now(), "state": "running", "errors": [],
+ "config": {"preset": args.preset, "workload": args.workload,
+ "cpu_mean_budget": args.cpu_mean_budget, "footprint_budget": args.footprint_budget},
+ "phases": [], "environment": {"os": platform.mac_ver()[0], "arch": platform.machine()},
+ "target": {"name": args.app.stem}}
+ exit_code = 0
+
+ def stop(signum, frame):
+ raise KeyboardInterrupt
+
+ signal.signal(signal.SIGTERM, stop)
+ try:
+ if platform.system() != "Darwin":
+ raise RuntimeError("Recording requires macOS and full Xcode")
+ data["tool_sha256"] = {}
+ source_directory = output / "tool-source"
+ source_directory.mkdir()
+ for name in ("run.py", "analyze.py", "report.py", "report.html"):
+ source = Path(__file__).with_name(name).read_bytes()
+ (source_directory / name).write_bytes(source)
+ data["tool_sha256"][name] = hashlib.sha256(source).hexdigest()
+ status("Preflight: target, Xcode, templates, schemas")
+ data["target"] = inspect_target(args.app.resolve(), args.pid)
+ env = data["environment"]
+ env["instruments"] = capture(["/usr/bin/xcrun", "xctrace", "version"])
+ env["chip"] = optional(["/usr/sbin/sysctl", "-n", "machdep.cpu.brand_string"])
+ env["cores"] = optional(["/usr/sbin/sysctl", "-n", "hw.logicalcpu"])
+ env["memory_bytes"] = optional(["/usr/sbin/sysctl", "-n", "hw.memsize"])
+ env["power"] = optional(["/usr/bin/pmset", "-g", "batt"])
+ env["power_source"] = (env["power"] or "Unknown").splitlines()[0]
+ env["load_before"] = list(os.getloadavg())
+ templates = capture(["/usr/bin/xcrun", "xctrace", "list", "templates"], timeout=60)
+ for template in ("Time Profiler", "Activity Monitor"):
+ if template not in templates.splitlines():
+ raise RuntimeError(f"Missing Instruments template: {template}")
+ schemas = load_schemas(capture(["/usr/bin/xcode-select", "-p"]))
+ (output / "schemas.json").write_text(json.dumps(schemas, indent=2))
+ warmup, sample, repeats, soak, settle = PRESETS[args.preset]
+ data["config"]["warmup_s"] = warmup
+ data["plan"] = [{"id": f"cpu-{i + 1}", "label": f"CPU repeat {i + 1}", "seconds": sample,
+ "template": "Time Profiler"} for i in range(repeats)] + [
+ {"id": "soak", "label": "Resource observation", "seconds": soak, "template": "Activity Monitor"},
+ {"id": "settle", "label": "Follow-up observation", "seconds": settle, "template": "Activity Monitor"}]
+ save(data, output)
+ status(f"Warm-up {warmup}s; target PID {data['target']['identity']['pid']}; output {output}")
+ time.sleep(warmup)
+ for planned in data["plan"]:
+ phase = dict(planned)
+ data["phases"].append(phase)
+ status(f"Recording {phase['id']} ({phase['template']}, {phase['seconds']}s)")
+ record_phase(phase, data, output, schemas)
+ status(f"Finished {phase['id']}: {'incomplete' if phase['errors'] else 'valid'}")
+ save(data, output)
+ data["state"] = "complete" if all(not p.get("errors") for p in data["phases"]) else "incomplete"
+ data["environment"]["load_after"] = list(os.getloadavg())
+ if args.baseline:
+ data["comparison"] = compare(data, args.baseline)
+ breached = []
+ for phase in data["phases"]:
+ resource = phase.get("resources", {})
+ if phase.get("errors"):
+ continue
+ if args.cpu_mean_budget is not None and resource.get("cpu_mean", 0) > args.cpu_mean_budget:
+ breached.append(phase["id"] + ": cpu_mean")
+ if args.footprint_budget is not None and resource.get("footprint", {}).get("max", 0) > args.footprint_budget:
+ breached.append(phase["id"] + ": footprint_peak")
+ data["budget_breaches"] = breached
+ exit_code = 2 if data["state"] != "complete" else 3 if breached else 0
+ except KeyboardInterrupt:
+ data["state"] = "interrupted"
+ data["errors"].append("Interrupted by operator; partial results retained")
+ exit_code = 130
+ except Exception as error:
+ data["state"] = "incomplete"
+ data["errors"].append(f"{type(error).__name__}: {error}")
+ exit_code = 2
+ finally:
+ data["ended"] = now()
+ data["exit_code"] = exit_code
+ try:
+ save(data, output)
+ except Exception as error:
+ data["errors"].append(f"Saving results failed: {type(error).__name__}: {error}")
+ data["state"] = "incomplete"
+ exit_code = data["exit_code"] = 2
+ for message in data["errors"]:
+ status(message)
+ try:
+ output = Path(tempfile.mkdtemp(prefix="codexbar-performance-recovery-"))
+ save(data, output)
+ except Exception as recovery_error:
+ status(f"Recovery save failed: {type(recovery_error).__name__}: {recovery_error}")
+ output = None
+ if output is not None:
+ status(f"Report: {output / 'report.html'}; exit {exit_code}")
+ return exit_code
+
+
+if __name__ == "__main__":
+ sys.exit(main())