* @param {string} name name * @param {() => void} fn function * @returns {Promise<void>} function wrapper in profiling code
(name, fn)
| 347 | * @returns {Promise<void>} function wrapper in profiling code |
| 348 | */ |
| 349 | async function withProfiling(name, fn) { |
| 350 | // Ensure the profiles directory exists |
| 351 | await fs.mkdir(path.join(baseOutputPath, "profiles"), { recursive: true }); |
| 352 | |
| 353 | const session = new Session(); |
| 354 | session.connect(); |
| 355 | |
| 356 | // Enable and start profiling |
| 357 | await new Promise( |
| 358 | /** |
| 359 | * @param {(val: void) => void} resolve resolve |
| 360 | * @param {(err?: Error) => void} reject reject |
| 361 | */ |
| 362 | (resolve, reject) => { |
| 363 | session.post("Profiler.enable", (err) => { |
| 364 | if (err) return reject(err); |
| 365 | session.post("Profiler.start", (err) => { |
| 366 | if (err) return reject(err); |
| 367 | resolve(); |
| 368 | }); |
| 369 | }); |
| 370 | } |
| 371 | ); |
| 372 | |
| 373 | // Run the benchmarked function |
| 374 | // No need to `console.time`, it'll be included in the |
| 375 | // CPU Profile. |
| 376 | await fn(); |
| 377 | |
| 378 | // Stop profiling and get the CPU profile |
| 379 | const profile = await new Promise((resolve, reject) => { |
| 380 | session.post("Profiler.stop", (err, { profile }) => { |
| 381 | if (err) return reject(err); |
| 382 | resolve(profile); |
| 383 | }); |
| 384 | }); |
| 385 | |
| 386 | session.disconnect(); |
| 387 | |
| 388 | const outputFile = `${sanitizeFilename(name)}-${Date.now()}.cpuprofile`; |
| 389 | |
| 390 | await fs.writeFile( |
| 391 | path.join(baseOutputPath, "profiles", outputFile), |
| 392 | JSON.stringify(profile), |
| 393 | "utf8" |
| 394 | ); |
| 395 | |
| 396 | console.log(`CPU profile saved to ${outputFile}`); |
| 397 | } |
| 398 | |
| 399 | /** |
| 400 | * @param {Webpack} webpack webpack |
no test coverage detected