我需要以毫秒为单位获取执行时间。

我最初问这个问题是在2008年。当时接受的答案是使用newDate().getTime()。然而,我们现在都可以同意使用标准performance.now()API更合适。因此,我将接受的答案改为这个答案。


当前回答

最好的方法是使用性能挂钩模块。虽然不稳定,但您可以标记代码的特定区域,并测量标记区域之间的持续时间。

const { performance, PerformanceObserver } = require('perf_hooks');

const measures = []

const obs = new PerformanceObserver(list => measures.push(...list.getEntries()));
obs.observe({ entryTypes: ['measure'] });
const getEntriesByType = cb => cb(measures);

const doSomething = val => {
  performance.mark('beginning of the process');

  val *= 2;

  performance.mark('after multiplication');

  performance.measure('time taken', 'beginning of the process', 'after multiplication');

  getEntriesByType(entries => {
    entries.forEach(entry => console.log(entry));
  })

  return val;
}

doSomething(4);

在此处尝试

其他回答

为了进一步扩展vsync的代码,以便能够在NodeJS中返回timeEnd作为值,请使用这段代码。

console.timeEndValue = function(label) { // Add console.timeEndValue, to add a return value
   var time = this._times[label];
   if (!time) {
     throw new Error('No such label: ' + label);
   }
   var duration = Date.now() - time;
   return duration;
};

现在使用如下代码:

console.time('someFunction timer');

someFunction();

var executionTime = console.timeEndValue('someFunction timer');
console.log("The execution time is " + executionTime);

这给了你更多的可能性。您可以存储执行时间以用于更多目的,如在公式中使用,或存储在数据库中,通过websocket发送到远程客户端,在网页上提供服务等。

要启动计时器,请使用console.time(“myTimer”);可选:要打印经过的时间,请使用console.timeLog(“myTimer”);最后,停止计时器并打印最终结果time:console.timeEnd(“myTimer”);

您可以在MDN和Node.js文档中阅读更多关于这一点的信息。

可在Chrome、Firefox、Opera和NodeJS上使用。(不在Edge或Internet Explorer上)。

要获得精确的值,您应该使用Performance接口。Firefox、Chrome、Opera和IE的现代版本都支持它。下面是如何使用它的示例:

var performance = window.performance;
var t0 = performance.now();
doWork();
var t1 = performance.now();
console.log("Call to doWork took " + (t1 - t0) + " milliseconds.")

Date.getTime()或console.time()不适合测量精确的执行时间。如果快速粗略估计对您来说合适,您可以使用它们。粗略估计,我的意思是你可以从实时得到15-60毫秒的偏移。

查看这篇关于测量JavaScript执行时间的精彩文章。作者还提供了一些关于JavaScript时间准确性的链接,值得一读。

它可能会帮助你。

var t0=date.now();做某事();var t1=date.now();console.log(“调用doSomething花费了大约”+(t1-t0)/1000+“秒”)

这是一个计时器功能。如果要测量未嵌套的多个对象之间的时间:

function timer(lap){ 
    if(lap) console.log(`${lap} in: ${(performance.now()-timer.prev).toFixed(3)}ms`); 
    timer.prev = performance.now();
}

类似于console.time(),但如果不需要跟踪以前的计时器,则更容易使用。


用法:

timer()              // set the start
// do something 
timer('built')       // logs 'built in: 591.815ms'
// do something
timer('copied')      // logs 'copied in: 0.065ms'
// do something
timer('compared')    // logs 'compared in: 36.41ms'

如果您喜欢console.time()中的蓝色,可以使用这行

console.log(`${lap} in: %c${(performance.now()-timer.prev).toFixed(3)}ms`, 'color:blue');