Instruments 性能分析(macOS/iOS)
当用户需要对原生应用进行性能分析或堆栈分析时使用此技能。
重点:Time Profiler、xctrace CLI 以及选择正确的二进制文件/应用实例。
快速开始(CLI)
- 列出模板:
xcrun xctrace list templates - 记录 Time Profiler(启动):
xcrun xctrace record --template 'Time Profiler' --time-limit 60s --output /tmp/App.trace --launch -- /path/To/App.app
- 记录 Time Profiler(附加):
- 自行启动应用,获取 PID,然后:
xcrun xctrace record --template 'Time Profiler' --time-limit 60s --output /tmp/App.trace --attach <pid>
- 在 Instruments 中打开跟踪:
open -a Instruments /tmp/App.trace
注意:xcrun xctrace --help 不是有效的子命令。请使用 xcrun xctrace help record。
选择正确的二进制文件(关键)
陷阱:Instruments 可能会分析错误的应用(例如,/Applications 中的那个),如果 LaunchServices 解析了不同的 bundle。
请使用以下规则:
- 优先使用直接二进制路径以实现确定性启动:
xcrun xctrace record ... --launch -- /path/App.app/Contents/MacOS/App
- 如果启动
.app,请确保它是预期的 bundle:open -n /path/App.app- 使用
ps -p <pid> -o comm= -o command=验证
- 如果
/Applications/App.app和本地构建同时存在,显式指定本地构建路径。 - 启动后,在信任跟踪之前确认进程路径。
命令参数(xctrace)
--template 'Time Profiler':来自xctrace list templates的模板名称。--launch -- <cmd>:--后的所有内容都是目标命令(二进制文件或应用 bundle)。--attach <pid|name>:附加到正在运行的进程。--output <path>:.trace输出。如果省略,文件保存在当前工作目录。--time-limit 60s|5m:设置捕获持续时间。--device <name|UDID>:iOS 设备运行必需。--target-stdout -:将启动进程的标准输出流式传输到终端(对 CLI 工具有用)。
导出堆栈(CLI)
- 检查跟踪表:
xcrun xctrace export --input /tmp/App.trace --toc
- 导出原始时间分析样本:
xcrun xctrace export --input /tmp/App.trace --xpath '/trace-toc/run[@number="1"]/data/table[@schema="time-profile"]' --output /tmp/time-profile.xml
- 在脚本(Python/Rust)中进行后处理以聚合堆栈。
Instruments UI 工作流
- 模板:Time Profiler
- 使用“记录”并捕获慢路径(启动 vs 稳态)
- 调用树提示:
- 隐藏系统库
- 反转调用树
- 按线程分离
- 关注热点框架和调用次数
陷阱与修复
- 分析到错误的应用:LaunchServices 解析已安装的应用而不是本机构建。
- 修复:使用直接二进制路径或通过已知 PID 的
--attach。
- 修复:使用直接二进制路径或通过已知 PID 的
- 无样本/空跟踪:应用快速退出或从未执行工作负载。
- 修复:更长的捕获时间,在录制期间触发工作负载。
- 隐私提示:
xctrace可能需要“开发者工具”权限。- 修复:系统设置 → 隐私与安全性 → 开发者工具 → 允许 Terminal/Xcode。
- 大型 XML 导出:
time-profile导出非常大。- 修复:使用 XPath 过滤并离线聚合;不要打印到终端。
iOS 相关说明
- 设备:使用
xcrun xctrace list devices和--device <UDID>。 - 如果需要,通过 Xcode 启动;使用
xctrace --attach附加。 - 确保有调试符号以获得有意义的堆栈。
验证检查清单
- 确认跟踪进程路径与目标构建匹配。
- 确认堆栈显示预期的应用框架。
- 捕获覆盖慢速操作(启动/刷新)。
- 导出堆栈以便在优化时进行自动差异比较。