测量异步操作的持续时间
\Measuring the duration of async operations
以下示例使用 异步钩子 和性能 API 来测量超时操作的实际持续时间(包括执行回调所花费的时间量)。
\The following example uses the Async Hooks and Performance APIs to measure the actual duration of a Timeout operation (including the amount of time it took to execute the callback).
import { createHook } from 'node:async_hooks'; import { performance, PerformanceObserver } from 'node:perf_hooks'; const set = new Set(); const hook = createHook({ init(id, type) { if (type === 'Timeout') { performance.mark(`Timeout-${id}-Init`); set.add(id); } }, destroy(id) { if (set.has(id)) { set.delete(id); performance.mark(`Timeout-${id}-Destroy`); performance.measure(`Timeout-${id}`, `Timeout-${id}-Init`, `Timeout-${id}-Destroy`); } }, }); hook.enable(); const obs = new PerformanceObserver((list, observer) => { console.log(list.getEntries()[0]); performance.clearMarks(); performance.clearMeasures(); observer.disconnect(); }); obs.observe({ entryTypes: ['measure'], buffered: true }); setTimeout(() => {}, 1000);'use strict'; const async_hooks = require('node:async_hooks'); const { performance, PerformanceObserver, } = require('node:perf_hooks'); const set = new Set(); const hook = async_hooks.createHook({ init(id, type) { if (type === 'Timeout') { performance.mark(`Timeout-${id}-Init`); set.add(id); } }, destroy(id) { if (set.has(id)) { set.delete(id); performance.mark(`Timeout-${id}-Destroy`); performance.measure(`Timeout-${id}`, `Timeout-${id}-Init`, `Timeout-${id}-Destroy`); } }, }); hook.enable(); const obs = new PerformanceObserver((list, observer) => { console.log(list.getEntries()[0]); performance.clearMarks(); performance.clearMeasures(); observer.disconnect(); }); obs.observe({ entryTypes: ['measure'] }); setTimeout(() => {}, 1000);