performance.timerify(fn[, options])
fn<Function>options<Object>histogram<RecordableHistogram> 使用perf_hooks.createHistogram()创建的直方图对象,用于记录以纳秒为单位的运行时持续时间。
此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
【This property is an extension by Node.js. It is not available in Web browsers.】
将一个函数封装在一个新函数中,该新函数会测量被封装函数的运行时间。必须订阅 'function' 事件类型的 PerformanceObserver,才能访问计时详情。
【Wraps a function within a new function that measures the running time of the
wrapped function. A PerformanceObserver must be subscribed to the 'function'
event type in order for the timing details to be accessed.】
import { performance, PerformanceObserver } from 'node:perf_hooks';
function someFunction() {
console.log('hello world');
}
const wrapped = performance.timerify(someFunction);
const obs = new PerformanceObserver((list) => {
console.log(list.getEntries()[0].duration);
performance.clearMarks();
performance.clearMeasures();
obs.disconnect();
});
obs.observe({ entryTypes: ['function'] });
// A performance timeline entry will be created
wrapped();const {
performance,
PerformanceObserver,
} = require('node:perf_hooks');
function someFunction() {
console.log('hello world');
}
const wrapped = performance.timerify(someFunction);
const obs = new PerformanceObserver((list) => {
console.log(list.getEntries()[0].duration);
performance.clearMarks();
performance.clearMeasures();
obs.disconnect();
});
obs.observe({ entryTypes: ['function'] });
// A performance timeline entry will be created
wrapped();如果被封装的函数返回一个 Promise,将会在该 Promise 上附加一个 finally 处理程序,并且一旦 finally 处理程序被调用,持续时间就会被报告。
【If the wrapped function returns a promise, a finally handler will be attached to the promise and the duration will be reported once the finally handler is invoked.】