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

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


当前回答

几个月前,我用Date.now()编写了自己的例程,对函数进行计时——尽管当时接受的方法似乎是performance.now(--因为性能对象在稳定的Node.js版本中还不可用(内置)。

今天我做了更多的研究,发现了另一种计时方法。由于我还发现了如何在Node.js代码中使用它,所以我想在这里分享一下。

以下内容结合了w3c和Node.js给出的示例:

function functionTimer() {
    performance.mark('start')
    functionToBeTimed()
    performance.mark('end')
    performance.measure('Start to End', 'start', 'end')
    const measure = performance.getEntriesByName('Start to End')[0]
    console.log(measure.duration)
}

注:

如果您打算在Node.js应用程序中使用性能对象,则必须包含以下要求:const{performance}=require('perf_hooks')

其他回答

要获得精确的值,您应该使用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时间准确性的链接,值得一读。

几个月前,我用Date.now()编写了自己的例程,对函数进行计时——尽管当时接受的方法似乎是performance.now(--因为性能对象在稳定的Node.js版本中还不可用(内置)。

今天我做了更多的研究,发现了另一种计时方法。由于我还发现了如何在Node.js代码中使用它,所以我想在这里分享一下。

以下内容结合了w3c和Node.js给出的示例:

function functionTimer() {
    performance.mark('start')
    functionToBeTimed()
    performance.mark('end')
    performance.measure('Start to End', 'start', 'end')
    const measure = performance.getEntriesByName('Start to End')[0]
    console.log(measure.duration)
}

注:

如果您打算在Node.js应用程序中使用性能对象,则必须包含以下要求:const{performance}=require('perf_hooks')

在函数之前使用console.time(“此处的某个标签”),在函数之后使用console.timeEnd(“此处某个标签)。它将为您提供函数的运行时间。

具有性能

NodeJs:需要导入性能类

var time0 = performance.now(); // Store the time at this point into time0

yourFunction();   // The function you're measuring time for 

var time1 = performance.now(); // Store the time at this point into time1

console.log("youFunction took " + (time1 - time0) + " milliseconds to execute");

使用console.time

console.time('someFunction');

someFunction(); // Whatever is timed goes between the two "console.time"

console.timeEnd('someFunction');

使用new Date().getTime()

getTime()方法返回自1970年1月1日午夜以来的毫秒数。

ex.

var start = new Date().getTime();

for (i = 0; i < 50000; ++i) {
// do something
}

var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);