示例工程 42-startup-and-memory
42-startup-and-memory/app/.tsc/main/index.js
import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { performance } from "node:perf_hooks";
import v8 from "node:v8";
import { assertPaintReq, assertSampleReq, CH, } from "../shared/ipc";
app.setName("Startup Memory Lab");
const isSmoke = process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
const tempData = isSmoke || isShots
? path.join(os.tmpdir(), `startup-${isSmoke ? "smoke" : "shots"}-${process.pid}`)
: "";
if (tempData)
app.setPath("userData", tempData);
const mainLoadedAt = Date.now();
const processStartAt = mainLoadedAt - process.uptime() * 1000;
const marks = new Map([["mainLoaded", mainLoadedAt]]);
let win = null;
let events = [];
let samples = [];
let allocatedMb = 0;
let heapSnapshot = null;
let throttle = null;
let throttleRunning = null;
let lazy = { status: "idle", ms: 0, readyAt: 0 };
let lazyStarted = false;
const STAGE_LABELS = [
["mainLoaded", "主进程模块加载"],
["appReady", "app ready"],
["windowCreated", "窗口创建"],
["didFinishLoad", "页面加载完成"],
["firstPaint", "首帧绘制"],
["readyToShow", "ready-to-show"],
];
const userData = app.getPath("userData");
function log(kind, detail) {
events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40);
broadcast();
}
function broadcast() {
if (win && !win.isDestroyed()) {
win.webContents.send("perf:event", { at: Date.now() });
}
}
function mark(key, at = Date.now()) {
if (!marks.has(key))
marks.set(key, at);
}
function startupInfo() {
const entries = [...marks.entries()]
.filter(([key]) => key !== "domContentLoaded")
.sort((a, b) => a[1] - b[1]);
let previous = processStartAt;
const stages = entries.map(([key, at]) => {
const label = STAGE_LABELS.find(([candidate]) => candidate === key)?.[1] ?? key;
const deltaMs = Math.max(0, at - previous);
previous = at;
return { key, label, at, deltaMs };
});
const firstPaintAt = marks.get("firstPaint") ?? marks.get("didFinishLoad") ?? Date.now();
const totalMs = Math.max(0, firstPaintAt - processStartAt);
return {
stages,
totalMs,
firstPaintMs: totalMs,
lazy: { ...lazy },
};
}
function processRows() {
return app.getAppMetrics().map((metric) => ({
type: metric.type,
pid: metric.pid,
workingSetMb: Number((metric.memory.workingSetSize / 1024).toFixed(1)),
peakMb: Number((metric.memory.peakWorkingSetSize / 1024).toFixed(1)),
cpu: Number((metric.cpu.percentCPUUsage ?? 0).toFixed(1)),
}));
}
function memoryInfo() {
const usage = process.memoryUsage();
const heap = v8.getHeapStatistics();
const processes = processRows();
const rendererMb = processes
.filter((row) => row.type === "Tab" || row.type === "Renderer")
.reduce((sum, row) => sum + row.workingSetMb, 0);
const totalMb = processes.reduce((sum, row) => sum + row.workingSetMb, 0);
return {
main: {
rssMb: Number((usage.rss / 1024 / 1024).toFixed(1)),
heapUsedMb: Number((usage.heapUsed / 1024 / 1024).toFixed(1)),
heapTotalMb: Number((usage.heapTotal / 1024 / 1024).toFixed(1)),
externalMb: Number((usage.external / 1024 / 1024).toFixed(1)),
heapLimitMb: Number((heap.heap_size_limit / 1024 / 1024).toFixed(1)),
},
rendererMb: Number(rendererMb.toFixed(1)),
totalMb: Number(totalMb.toFixed(1)),
allocatedMb,
processes,
samples: samples.map((sample) => ({ ...sample })),
heapSnapshot,
};
}
function snapshot() {
return {
platform: process.platform,
electronVersion: process.versions.electron,
nodeVersion: process.versions.node,
startup: startupInfo(),
memory: memoryInfo(),
throttle,
events: events.map((row) => ({ ...row })),
};
}
function sample(nextAllocated) {
const info = memoryInfo();
allocatedMb = nextAllocated;
samples = [
...samples,
{
at: Date.now(),
mainHeapMb: info.main.heapUsedMb,
mainRssMb: info.main.rssMb,
rendererMb: info.rendererMb,
totalMb: info.totalMb,
allocatedMb: nextAllocated,
},
].slice(-30);
log("sample", `main ${info.main.heapUsedMb}MB · renderer ${info.rendererMb}MB · allocated ${nextAllocated}MB`);
}
function buildIndex() {
lazy = { ...lazy, status: "building" };
const started = performance.now();
let value = 0;
for (let index = 0; index < 3_000_000; index += 1) {
value = (value + index * 31) % 1_000_003;
}
lazy = {
status: "ready",
ms: Number((performance.now() - started).toFixed(2)),
readyAt: Date.now(),
};
log("lazy", `延迟索引构建完成 · ${lazy.ms}ms · ${value}`);
}
function scheduleLazy() {
if (lazyStarted)
return;
lazyStarted = true;
setTimeout(() => buildIndex(), 30);
}
async function runThrottleTest() {
if (throttleRunning)
return throttleRunning;
throttleRunning = (async () => {
const html = "<html><body><script>window.__ticks=0;setInterval(function(){window.__ticks++},50);</script></body></html>";
const create = (enabled) => new BrowserWindow({
width: 420,
height: 300,
show: false,
webPreferences: {
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
webSecurity: true,
allowRunningInsecureContent: false,
experimentalFeatures: false,
webviewTag: false,
spellcheck: false,
backgroundThrottling: enabled,
},
});
const throttled = create(true);
const unthrottled = create(false);
try {
await Promise.all([
throttled.loadURL(`data:text/html,${html}`),
unthrottled.loadURL(`data:text/html,${html}`),
]);
const started = Date.now();
await new Promise((resolve) => setTimeout(resolve, 2000));
const trueTicks = await throttled.webContents.executeJavaScript("window.__ticks");
const falseTicks = await unthrottled.webContents.executeJavaScript("window.__ticks");
const result = {
trueTicks: Number(trueTicks),
falseTicks: Number(falseTicks),
durationMs: Date.now() - started,
at: Date.now(),
};
throttle = result;
log("throttle", `hidden throttle ${result.trueTicks} vs ${result.falseTicks}`);
return result;
}
finally {
throttled.destroy();
unthrottled.destroy();
throttleRunning = null;
}
})();
return throttleRunning;
}
function writeHeapSnapshot() {
const file = path.join(userData, `heap-${Date.now()}.heapsnapshot`);
v8.writeHeapSnapshot(file);
const bytes = fsSync.statSync(file).size;
heapSnapshot = {
file: `userData/${path.basename(file)}`,
bytes,
at: Date.now(),
};
log("heap", `heap snapshot ${(bytes / 1024 / 1024).toFixed(1)}MB`);
}
function resolvePreload() {
const candidates = [
path.join(__dirname, "preload.cjs"),
path.join(__dirname, "../preload/index.cjs"),
path.join(__dirname, "preload.js"),
];
return (candidates.find((candidate) => fsSync.existsSync(candidate)) ??
candidates[0] ??
"");
}
function createWindow() {
const window = new BrowserWindow({
width: 1100,
height: 860,
show: false,
title: "启动与内存实验室",
backgroundColor: "#ffffff",
webPreferences: {
preload: resolvePreload(),
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
webSecurity: true,
allowRunningInsecureContent: false,
experimentalFeatures: false,
webviewTag: false,
spellcheck: false,
backgroundThrottling: true,
},
});
mark("windowCreated");
window.once("ready-to-show", () => {
mark("readyToShow");
window.show();
});
window.webContents.once("did-finish-load", () => {
mark("didFinishLoad");
if (!window.isDestroyed() && !window.isVisible())
window.show();
sample(0);
log("ready", "渲染进程加载完成");
});
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
void window.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
}
else {
void window.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`));
}
win = window;
return window;
}
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function evalRenderer(window, code) {
let lastError = null;
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
return (await window.webContents.executeJavaScript(code));
}
catch (caught) {
lastError = caught;
await delay(200);
}
}
throw lastError instanceof Error ? lastError : new Error(String(lastError));
}
async function waitForRenderer(window) {
for (let attempt = 0; attempt < 160; attempt += 1) {
if (window.isDestroyed())
return;
try {
const ready = await evalRenderer(window, "typeof window.__smoke === 'function'");
if (ready)
return;
}
catch {
// 页面仍在加载。
}
await delay(100);
}
throw new Error("renderer did not become ready");
}
async function runSmoke(window) {
try {
await waitForRenderer(window);
await delay(800);
await waitForRenderer(window);
const result = await evalRenderer(window, "window.__smoke()");
process.stdout.write(`${JSON.stringify({
evt: "smoke",
ok: result.startupTotal > 0 &&
result.stageCount >= 5 &&
result.firstPaint > 0 &&
result.mainHeap > 0 &&
result.rendererMb > 0 &&
result.processCount >= 2 &&
result.sampleCount >= 3 &&
result.allocatedMb >= 24 &&
result.trueTicks > 0 &&
result.falseTicks > 0 &&
result.throttleDuration >= 1800 &&
result.lazyStatus === "ready" &&
result.lazyMs > 0 &&
result.events >= 4,
...result,
})}\n`);
app.quit();
}
catch (caught) {
process.stdout.write(`${JSON.stringify({ evt: "smoke", ok: false, message: String(caught) })}\n`);
app.exit(1);
}
}
async function capture(window, dir, file) {
const image = await window.webContents.capturePage();
if (image.isEmpty())
throw new Error(`empty capture: ${file}`);
const png = image.toPNG();
fsSync.writeFileSync(path.join(dir, file), png);
fsSync.writeFileSync(path.join(dir, "raw", file), png);
}
async function runShots(window) {
try {
const dir = path.resolve(process.cwd(), "../../../docs/assets/images/42-startup-and-memory");
fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
await waitForRenderer(window);
await delay(900);
await waitForRenderer(window);
await evalRenderer(window, `window.__prepareShots("startup")`);
await delay(400);
await capture(window, dir, "42-01-startup.png");
await evalRenderer(window, `window.__prepareShots("memory")`);
await delay(500);
await capture(window, dir, "42-02-memory.png");
await evalRenderer(window, `window.__prepareShots("throttle")`);
await delay(2300);
await capture(window, dir, "42-03-throttle.png");
app.quit();
}
catch (caught) {
process.stdout.write(`${JSON.stringify({ evt: "shots-error", message: String(caught) })}\n`);
app.exit(1);
}
}
ipcMain.handle(CH.snapshot, () => snapshot());
ipcMain.handle(CH.sample, (_event, raw) => {
assertSampleReq(raw);
sample(raw.allocatedMb);
return snapshot();
});
ipcMain.handle(CH.throttle, async () => {
await runThrottleTest();
return snapshot();
});
ipcMain.handle(CH.heap, () => {
writeHeapSnapshot();
return snapshot();
});
ipcMain.handle(CH.lazy, () => {
buildIndex();
return snapshot();
});
ipcMain.handle(CH.paint, (_event, raw) => {
assertPaintReq(raw);
mark("firstPaint", raw.firstPaint);
mark("domContentLoaded", raw.domContentLoaded);
scheduleLazy();
log("paint", `firstPaint ${Math.round(raw.firstPaint - processStartAt)}ms · DCL ${Math.round(raw.domContentLoaded - processStartAt)}ms`);
return snapshot();
});
ipcMain.handle(CH.refresh, () => {
log("refresh", "刷新启动与内存状态");
return snapshot();
});
app.whenReady().then(() => {
mark("appReady");
const window = createWindow();
if (isSmoke) {
void runSmoke(window);
}
else if (isShots) {
void runShots(window);
}
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
else {
win?.show();
win?.focus();
}
});
});
app.on("will-quit", () => {
if (tempData) {
try {
fsSync.rmSync(tempData, { recursive: true, force: true });
}
catch {
// 清理失败不影响退出。
}
}
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin")
app.quit();
});
//# sourceMappingURL=index.js.map