示例工程 42-startup-and-memory

42-startup-and-memory/demo-01-startup-budget/budget.ts

typescript · 1.6 KB

type Marks = {
  processStart: number;
  mainLoaded: number;
  appReady: number;
  windowCreated: number;
  readyToShow: number;
  didFinishLoad: number;
  firstPaint: number;
};

type Stage = { key: string; at: number; deltaMs: number };

function stages(marks: Marks): { stages: Stage[]; totalMs: number } {
  const order: Array<[keyof Marks, string]> = [
    ["mainLoaded", "主进程模块加载"],
    ["appReady", "app ready"],
    ["windowCreated", "窗口创建"],
    ["readyToShow", "ready-to-show"],
    ["firstPaint", "首帧绘制"],
    ["didFinishLoad", "页面加载完成"],
  ];
  let previous = marks.processStart;
  const result = order
    .map(([key]) => {
      const at = marks[key];
      const deltaMs = Math.max(0, at - previous);
      previous = at;
      return { key, at, deltaMs };
    })
    .filter((stage) => stage.at > 0);
  return {
    stages: result,
    totalMs: Math.max(0, marks.firstPaint - marks.processStart),
  };
}

const marks: Marks = {
  processStart: 0,
  mainLoaded: 110,
  appReady: 240,
  windowCreated: 420,
  readyToShow: 550,
  firstPaint: 560,
  didFinishLoad: 620,
};

const normal = stages(marks);
const budgetOk = normal.totalMs <= 800;
const budgetBad = normal.totalMs > 500;

const ok =
  normal.totalMs === 560 &&
  normal.stages.length === 6 &&
  normal.stages[0]?.deltaMs === 110 &&
  normal.stages[1]?.deltaMs === 130 &&
  normal.stages[4]?.deltaMs === 10 &&
  budgetOk &&
  budgetBad;

console.log(
  JSON.stringify({
    evt: "smoke",
    ok,
    totalMs: normal.totalMs,
    stages: normal.stages,
    budget: { limit: 800, ok: budgetOk },
  }),
);