假设我调用了一个函数作为,
const data = await someFunction()
我想计算这个函数的执行时间。
为此,我尝试了
let startTime = Date.now();
const data = await someFunction()
let endTime = Date.now();
我计算了endTimestartTime和我得到的结果之间的差值,我认为是以毫秒为单位,并将其转换为秒。
我想就这一点发表第二意见,无论这是计算的选项之一,还是有更好的方法可以在几秒钟内给我执行时间。
是的,还有几个更有趣的方法:
-
在节点中进行测试的更准确方法是使用:
const start = process.hrtime() // awaited function const result = process.hrtime(start); // This will give results in nanoseconds
-
另一种有趣的方法是使用性能挂钩:
const { PerformanceObserver, performance } = require('perf_hooks'); const obs = new PerformanceObserver((items) => { console.log(items.getEntries()[0].duration); performance.clearMarks(); }); obs.observe({ entryTypes: ['measure'] }); performance.mark('A'); // await your function performance.mark('B'); performance.measure('A to B', 'A', 'B');
您一直在尝试console.time((吗?
console.time("Some Function time");
const data = await someFunction()
console.timeEnd("Some Function time");