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

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


当前回答

有多种方法可以实现这一目标:

使用console.timeconsole.time(“函数”);//在这两行之间运行函数//测量函数所用的时间。(“例如函数();”)console.timeEnd('功能');这是最有效的方法:使用performance.now(),例如。var v1=performance.now();//在这里运行您可以测量时间的函数var v2=性能.now();console.log(“总时间=”+(v2-v1)+“毫秒”);使用+(add运算符)或getTime()var h2=+新日期()//或var h2=新日期().getTime();对于(i=0;i<500;i++){/*做某事*/}var h3=+新日期()//或var h3=新日期().getTime();var timeTaken=h3-h2;console.log(“time===”,timeTaken);

以下是将一元加号运算符应用于Date实例时的情况:获取相关Date实例的值将其转换为数字

注意:getTime()比一元+运算符提供更好的性能。

其他回答

为了进一步扩展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发送到远程客户端,在网页上提供服务等。

公认的答案是错误的!

由于JavaScript是异步的,因此接受的答案的变量端的值将是错误的。

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

for (i = 0; i < 50000; ++i) {
// JavaScript is not waiting until the for is finished !!
}

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

for的执行速度可能非常快,因此您无法看到结果是错误的。您可以使用执行某些请求的代码来测试它:

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

for (i = 0; i < 50000; ++i) {
  $.ajax({
    url: 'www.oneOfYourWebsites.com',
    success: function(){
       console.log("success");
    }
  });
}

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

因此,警报将非常迅速地提示,但在控制台中,您将看到ajax请求正在继续。

以下是您应该如何做到的:https://developer.mozilla.org/en-US/docs/Web/API/Performance.now

具有性能

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');

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

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);

在此处尝试

它可能会帮助你。

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