调试与 Profiling 工具链
本章目标
- 掌握主进程、渲染进程、GPU 进程的调试入口。
- 会用 DevTools Performance/Memory、Chromium tracing、Instruments、WPT 定位性能问题。
- 能通过 CDP 自动化采集性能数据,接入 CI。
- 建立「高 CPU / 高内存 / 磁盘 IO / 网络异常」的排查决策树。
调试地图
主进程调试
启动调试端口
1npx electron --inspect=9229 .
2npx electron --inspect-brk=9229 . # 在第一行暂停,适合调试启动流程
VS Code 配置
1{
2 "version": "0.2.0",
3 "configurations": [
4 {
5 "name": "Electron: Main",
6 "type": "node",
7 "request": "launch",
8 "cwd": "${workspaceFolder}",
9 "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
10 "windows": {
11 "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
12 },
13 "args": [".", "--inspect=9229"],
14 "sourceMaps": true,
15 "outFiles": ["${workspaceFolder}/dist/**/*.js"]
16 }
17 ]
18}
如果主进程由 Vite/esbuild 构建,需要确保生成 source map,并在 outFiles 中覆盖产物目录。
调试启动阶段
--inspect-brk 会在入口第一行暂停,适合排查:
- 启动即崩溃。
- 某个模块加载时报错。
- 窗口创建顺序问题。
注意:生产包应通过 Fuses 关闭 EnableNodeCliInspectArguments,防止被附加调试器。
渲染进程调试
DevTools
1win.webContents.openDevTools({ mode: 'detach' });
也可以用快捷键:
1win.webContents.on('before-input-event', (event, input) => {
2 if (input.control && input.shift && input.key.toLowerCase() === 'i') {
3 win.webContents.toggleDevTools();
4 event.preventDefault();
5 }
6});
远程调试
1npx electron --remote-debugging-port=9222 .
在 Chrome 打开 chrome://inspect,可以:
- 检查页面、Console、Network。
- 采集 Performance trace。
- 附加到渲染进程的 Node inspector(如果开启了
--inspect)。
生产环境可通过 app.commandLine.appendSwitch 或 Fuses 控制是否允许。
DevTools 实战
Performance 面板
关注:
| 区域 | 内容 |
|---|
| Frames | 每帧耗时、掉帧标记 |
| Main | 主线程火焰图:JS、Style、Layout、Paint |
| Compositor | 合成线程 |
| GPU | GPU 进程任务 |
| Network | 资源加载 |
| Memory | 堆与 GC |
常用操作:
- 勾选 Screenshots,回看每一帧画面。
- 用
Cmd/Ctrl + F 搜索长任务或具体函数。
- 选中一段区间,看 Bottom-Up 排序。
- 保存 profile,便于对比优化前后。
Memory 面板
- Heap snapshot:对象级分析,适合泄漏。
- Allocation instrumentation on timeline:看分配热点。
- Allocation sampling:低开销采样,适合长时间录制。
Rendering 面板
- Paint flashing:定位不必要的重绘。
- Layout Shift Regions:定位布局偏移。
- Frame rendering stats:实时 FPS。
- Layer borders:合成层数量与边界。
Chromium tracing
代码采集
1import { app, contentTracing } from 'electron';
2import path from 'node:path';
3
4export async function startTrace(): Promise<void> {
5 await contentTracing.startRecording({
6 included_categories: [
7 'toplevel',
8 'v8',
9 'v8.execute',
10 'blink',
11 'blink.user_timing',
12 'renderer',
13 'gpu',
14 'disabled-by-default-devtools.timeline',
15 ],
16 });
17}
18
19export async function stopTrace(name: string): Promise<string> {
20 const file = path.join(app.getPath('temp'), `${name}.json`);
21 await contentTracing.stopRecording(file);
22 return file;
23}
命令行采集
1npx electron --trace-startup=./trace.json .
分析
把 trace 拖进:
重点看:
- 主进程主线程的长任务。
- 渲染进程的
RunTask、FunctionCall、Layout、Paint。
- GPU 进程的
Composite、Raster。
- 进程间 IPC 的等待时间。
系统级工具
macOS:Instruments
| 模板 | 用途 |
|---|
| Time Profiler | CPU 热点,按调用栈聚合 |
| Allocations | 对象分配与存活 |
| Leaks | 泄漏检测 |
| Core Animation | 帧率、合成、离屏渲染 |
| File Activity | 磁盘 IO |
使用步骤:
- 选择目标进程(Electron 主进程或渲染进程)。
- 录制复现场景。
- 在 Call Tree 中勾选 Invert Call Tree、Hide System Libraries。
- 定位热点函数。
Windows:Windows Performance Toolkit
1# 采集
2wpr -start CPU -start GPU -start FileIO -filemode
3
4# 复现问题后停止
5wpr -stop trace.etl
用 WPA 打开 .etl,重点看:
- CPU Usage (Sampled):CPU 热点。
- GPU Usage:GPU 占用。
- Disk Usage:磁盘 IO。
- Generic Events:ETW 事件。
Linux:Perf / Massif
1perf record -g -p <pid>
2perf report
3
4valgrind --tool=massif ./my-electron-app
5ms_print massif.out.<pid>
Linux 桌面场景较少,但服务器端 Electron 或 CI 环境可以用这些工具。
高 CPU 排查
主进程 CPU Profile
1npx electron --inspect=9229 .
在 Chrome chrome://inspect 中:
- 选择主进程目标。
- 打开 Profiler。
- Start → 复现 → Stop。
- 看火焰图中占比最高的函数。
也可以用 CDP 脚本采集,见下一节。
渲染进程高 CPU 的常见原因
setInterval 轮询过密。
- 动画使用
setTimeout 而非 requestAnimationFrame。
- 大列表全量重渲染。
- 频繁布局读取导致强制同步布局。
- 大量网络请求或 WebSocket 消息处理。
磁盘 IO 与网络
磁盘 IO
- 用 Instruments File Activity / WPA Disk Usage 看读写热点。
- 检查主进程是否有同步读写。
- 大文件使用流式处理。
- 日志写入使用缓冲与批量落盘。
1import { createWriteStream } from 'node:fs';
2
3const stream = createWriteStream(logPath, { flags: 'a' });
4stream.write(line);
网络
- DevTools Network 面板看请求瀑布。
- 主进程的
net 请求不会出现在渲染进程 Network 面板,需要单独打点。
- 使用
session.defaultSession.webRequest 记录请求耗时。
- 检查代理、DNS、证书、CSP 导致的失败。
1session.defaultSession.webRequest.onCompleted((details) => {
2 if (details.statusCode >= 400) {
3 console.warn('request failed', details.url, details.statusCode);
4 }
5});
请求劫持排查
如果请求被篡改或阻塞:
- 检查是否注册了
webRequest.onBeforeRequest 并返回了 cancel。
- 检查代理配置与系统代理。
- 检查 CSP 与 CORS。
- 检查是否有第三方安全软件注入。
自动化 Profiling 工具链
目标:把「打开 DevTools 手动点」变成「一条命令产出报告」。
通过 CDP 采集渲染进程指标
1// scripts/profile-renderer.ts
2import { app, BrowserWindow } from 'electron';
3
4export async function collectRendererMetrics(win: BrowserWindow): Promise<Record<string, number>> {
5 const debuggerApi = win.webContents.debugger;
6 debuggerApi.attach('1.3');
7
8 await debuggerApi.sendCommand('Performance.enable');
9 const { metrics } = (await debuggerApi.sendCommand('Performance.getMetrics')) as {
10 metrics: Array<{ name: string; value: number }>;
11 };
12
13 debuggerApi.detach();
14
15 return Object.fromEntries(metrics.map((m) => [m.name, m.value]));
16}
可以采集的指标包括 ScriptDuration、LayoutDuration、RecalcStyleDuration、TaskDuration、JSHeapUsedSize 等。
采集主进程 CPU Profile
1// scripts/profile-main.ts
2import { app } from 'electron';
3
4export async function profileMain(durationMs = 5000): Promise<unknown> {
5 const inspector = await import('node:inspector');
6 const session = new inspector.Session();
7 session.connect();
8
9 const post = (method: string, params?: object): Promise<unknown> =>
10 new Promise((resolve, reject) => {
11 session.post(method, params ?? {}, (err, result) => {
12 if (err) reject(err);
13 else resolve(result);
14 });
15 });
16
17 await post('Profiler.enable');
18 await post('Profiler.start');
19 await new Promise((resolve) => setTimeout(resolve, durationMs));
20 const { profile } = (await post('Profiler.stop')) as { profile: unknown };
21
22 session.disconnect();
23 return profile;
24}
把 profile 写入 .cpuprofile 文件,可直接拖进 DevTools Performance 或 Chrome Profiler 查看。
统一采集脚本
1// scripts/collect.ts
2import { app } from 'electron';
3import fs from 'node:fs/promises';
4import path from 'node:path';
5import { sampleProcessMemory } from '../src/main/perf/memory';
6
7export async function collectReport(outDir: string): Promise<void> {
8 const samples: unknown[] = [];
9
10 for (let i = 0; i < 20; i += 1) {
11 samples.push({
12 t: Date.now(),
13 processes: sampleProcessMemory(),
14 });
15 await new Promise((resolve) => setTimeout(resolve, 500));
16 }
17
18 await fs.mkdir(outDir, { recursive: true });
19 await fs.writeFile(
20 path.join(outDir, `memory-${app.getVersion()}.json`),
21 JSON.stringify(samples, null, 2),
22 );
23}
接入 CI
1- name: Performance smoke
2 run: |
3 npm run build
4 xvfb-run -a npx electron scripts/perf-main.js
5 node scripts/check-perf.js
CI 环境需要注意:
- 使用固定机型/固定镜像,减少噪声。
- 每次至少采集 3 次,取中位数。
- 只对「相对基线」做门禁,不要用绝对值卡死。
- 失败时上传 trace 与内存报告作为 artifact。
线上问题诊断
必要信息采集
1export function collectSystemInfo(): Record<string, string> {
2 return {
3 appVersion: app.getVersion(),
4 electron: process.versions.electron,
5 chrome: process.versions.chrome,
6 node: process.versions.node,
7 platform: process.platform,
8 arch: process.arch,
9 osVersion: process.getSystemVersion(),
10 locale: app.getLocale(),
11 };
12}
诊断包
建议支持「一键导出诊断包」:
- 应用日志(脱敏)。
- 最近崩溃报告。
- 系统信息。
- 当前进程内存指标。
- 关键配置(脱敏)。
- 可选:trace 文件。
常见问题定位表
| 现象 | 首选工具 | 重点看 |
|---|
| 启动慢 | --trace-startup | 主进程初始化、渲染加载 |
| 越用越卡 | DevTools Memory | 堆增长、Detached DOM |
| 滚动掉帧 | Performance | Layout、Paint、长任务 |
| 点击无响应 | Performance | 长任务、INP |
| CPU 持续高 | CPU Profile | 轮询、动画、重计算 |
| 内存高 | app.getAppMetrics | 哪个进程增长 |
| 崩溃 | minidump + 符号 | 崩溃线程与模块 |
| 白屏 | DevTools Console/Network | 资源失败、CSP、路径 |
本章小结
- 主进程用
--inspect,渲染进程用 DevTools,GPU/系统问题用 tracing 与系统工具。
- Performance 面板是渲染问题的第一入口,先看长任务与流水线阶段。
- Chromium tracing 能同时看到主进程、渲染进程、GPU 的时间线。
- CDP 可以把性能采集自动化,接入 CI 做回归门禁。
- 排查顺序应该是「进程 → 线程 → 阶段 → 函数」,不要一上来就猜代码。
参考资料