示例工程 42-startup-and-memory

42-startup-and-memory/demo-02-memory-trend/trend.ts

typescript · 1.1 KB

type Sample = { at: number; heapMb: number };

function estimateLeak(
  samples: Sample[],
  thresholdMbPerSample: number,
): { slope: number; leaking: boolean; first: number; last: number } {
  if (samples.length < 2) {
    return { slope: 0, leaking: false, first: 0, last: 0 };
  }
  const first = samples[0]?.heapMb ?? 0;
  const last = samples[samples.length - 1]?.heapMb ?? 0;
  const slope = (last - first) / (samples.length - 1);
  return {
    slope,
    leaking: slope >= thresholdMbPerSample,
    first,
    last,
  };
}

const growing: Sample[] = [10, 12, 14, 16, 18].map((heapMb, index) => ({
  at: index * 1000,
  heapMb,
}));
const flat: Sample[] = [10, 10.1, 10.2, 10.15, 10.2].map((heapMb, index) => ({
  at: index * 1000,
  heapMb,
}));

const growth = estimateLeak(growing, 1);
const stable = estimateLeak(flat, 1);

const ok =
  growth.leaking &&
  Math.abs(growth.slope - 2) < 1e-9 &&
  growth.first === 10 &&
  growth.last === 18 &&
  !stable.leaking &&
  Math.abs(stable.slope - 0.05) < 1e-9;

console.log(
  JSON.stringify({
    evt: "smoke",
    ok,
    growth,
    stable,
    threshold: 1,
  }),
);