计算函数的总执行时间

时间:2021-04-19 10:19:30

标签: javascript

const {performance} = require('perf_hooks');
let startTime = performance.now();
const extractedData = await readFunction()
let endTime = performance.now();
let timeTaken = endTime-startTime

我想计算执行 readFunction() 所需的时间。这是计算执行 readFunction 所需总时间的好方法吗?同样在 console.log(startTime) 上,它给出了一些值,而不是从 0 开始。

所以要获得精确的值,我应该执行以下步骤或以上步骤足以获得以毫秒为单位的精确时间。

const {performance} = require('perf_hooks');
let startTime = 0
const extractedData = await readFunction()
let endTime = performance.now();
let timeTaken = endTime-startTime

timeTaken 值是否以毫秒为单位?如果有人需要任何进一步的信息,请告诉我。

1 个答案:

答案 0 :(得分:0)

function calculateTime(yourFunction) {
  console.time();
  yourFunction();
  return console.timeEnd();
}
async function calculateTimeForPromises(yourPromise) {
  console.time();
  await yourPromise();
  return console.timeEnd();
}

有用吗?

相关问题