worker.startCpuProfile([options])


  • options <Object>
    • sampleInterval <number> 请求的采样间隔(毫秒)。默认值: 0
    • maxBufferSize <integer> 要保留的最大样本数量。 默认值: 4294967295
  • 返回:<Promise>

启动 CPU 分析,然后返回一个 Promise,该 Promise 会以错误或 CPUProfileHandle 对象作为结果。此 API 支持 await using 语法。

🌐 Starting a CPU profile then return a Promise that fulfills with an error or an CPUProfileHandle object. This API supports await using syntax.

const { Worker } = require('node:worker_threads');

const worker = new Worker(`
  const { parentPort } = require('worker_threads');
  parentPort.on('message', () => {});
  `, { eval: true });

worker.on('online', async () => {
  const handle = await worker.startCpuProfile({ sampleInterval: 1 });
  const profile = await handle.stop();
  console.log(profile);
  worker.terminate();
}); 

await using 示例。

const { Worker } = require('node:worker_threads');

const w = new Worker(`
  const { parentPort } = require('node:worker_threads');
  parentPort.on('message', () => {});
  `, { eval: true });

w.on('online', async () => {
  // Stop profile automatically when return and profile will be discarded
  await using handle = await w.startCpuProfile();
});