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 解析到不同的套件。
請遵循以下規則:
- 偏好直接使用二進位檔路徑進行確定性啟動:
xcrun xctrace record ... --launch -- /path/App.app/Contents/MacOS/App
- 如果啟動
.app,請確認它是預期的套件:open -n /path/App.app- 使用
ps -p <pid> -o comm= -o command=驗證
- 如果
/Applications/App.app與本地建置版本同時存在,請明確指定本地建置路徑。 - 啟動後,請先確認程序路徑再信任追蹤結果。
命令引數 (xctrace)
--template 'Time Profiler':來自xctrace list templates的範本名稱。--launch -- <cmd>:--之後的所有內容都是目標命令(二進位檔或應用程式套件)。--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可能需要「開發者工具」權限。- 解決方案:系統設定 → 隱私權與安全性 → 開發者工具 → 允許終端機/Xcode。
- 大量 XML 匯出:
time-profile匯出檔案很大。- 解決方案:使用 XPath 篩選並離線聚合;不要列印到終端機。
iOS 特定注意事項
- 裝置:使用
xcrun xctrace list devices與--device <UDID>。 - 如有需要,可透過 Xcode 啟動;使用
xctrace --attach附加。 - 確保除錯符號存在以獲得有意義的堆疊。
驗證檢查清單
- 確認追蹤程序路徑與目標建置路徑相符。
- 確認堆疊顯示預期的應用程式框架。
- 擷取範圍涵蓋慢速操作(啟動/重新整理)。
- 匯出堆疊以進行自動化差異比對(若正在進行最佳化)。