From 177d5dc636c4126d7d1bd92bcad9ec7ab8f8d62e Mon Sep 17 00:00:00 2001 From: theanarkh Date: Sat, 30 Aug 2025 01:30:28 +0800 Subject: [PATCH] worker: optimize cpu profile implement --- doc/api/v8.md | 27 +++++++++++ doc/api/worker_threads.md | 27 ++++++++--- lib/internal/worker.js | 61 ++++++++++++++---------- src/env.cc | 20 ++++---- src/env.h | 6 +-- src/node_errors.h | 1 - src/node_worker.cc | 27 +++++------ test/parallel/test-worker-cpu-profile.js | 42 +++------------- tools/doc/type-parser.mjs | 1 + typings/internalBinding/worker.d.ts | 7 ++- 10 files changed, 119 insertions(+), 100 deletions(-) diff --git a/doc/api/v8.md b/doc/api/v8.md index 90f8a815d26898..0e18b6b6c59522 100644 --- a/doc/api/v8.md +++ b/doc/api/v8.md @@ -1398,6 +1398,33 @@ setTimeout(() => { }, 1000); ``` +## Class: `CPUProfileHandle` + + + +### `cpuProfileHandle.stop()` + + + +* Returns: {Promise} + +Stopping collecting the profile, then return a Promise that fulfills with an error or the +profile data. + +### `cpuProfileHandle[Symbol.asyncDispose]()` + + + +* Returns: {Promise} + +Stopping collecting the profile and the profile will be discarded. + ## `v8.isStringOneByteRepresentation(content)` -* name: {string} * Returns: {Promise} -Starting a CPU profile with the given `name`, then return a Promise that fulfills -with an error or an object which has a `stop` method. Calling the `stop` method will -stop collecting the profile, then return a Promise that fulfills with an error or the -profile data. +Starting a CPU profile then return a Promise that fulfills with an error +or an `CPUProfileHandle` object. This API supports `await using` syntax. ```cjs const { Worker } = require('node:worker_threads'); @@ -1981,13 +1978,29 @@ const worker = new Worker(` `, { eval: true }); worker.on('online', async () => { - const handle = await worker.startCpuProfile('demo'); + const handle = await worker.startCpuProfile(); const profile = await handle.stop(); console.log(profile); worker.terminate(); }); ``` +`await using` example. + +```cjs +const { Worker } = require('node::worker_threads'); + +const w = new Worker(` + const { parentPort } = require('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(); +}); +``` + ### `worker.stderr`