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

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


当前回答

不要使用Date()。阅读以下内容。

使用performance.now():

<script>
var a = performance.now();
alert('do something...');
var b = performance.now();
alert('It took ' + (b - a) + ' ms.');
</script>

它适用于:

即10++火狐15++铬24++Safari 8++歌剧15++Android 4.4++等等

console.time对你来说可能可行,但它是非标准的§:

此功能是非标准的,不在标准轨道上。不要在面向Web的生产网站上使用它:它不会对每个用户都有效。实现之间也可能存在很大的不兼容性,并且行为可能会在未来发生变化。

除了浏览器支持之外,performance.now似乎有可能提供更准确的计时,因为它似乎是console.time的基本版本。


<rant>此外,不要将Date用于任何事情,因为它会受到“系统时间”变化的影响。这意味着当用户没有准确的系统时间时,我们将得到无效的结果,如“负计时”:

2014年10月,我的系统时钟失控了,猜猜怎么了。。。。我打开Gmail,看到我一天的所有电子邮件都是“0分钟前发送的”。我还以为Gmail应该是由谷歌的世界级工程师建造的。。。。。。。

(将你的系统时钟设置为一年前,然后转到Gmail,这样我们都可以开怀大笑。也许有一天,我们会为JS Date举办一个“耻辱大厅”。)

Google Spreadsheet的now()函数也存在此问题。

您将使用Date的唯一时间是您想向用户显示其系统时钟时间的时间。当你想得到时间或测量任何东西时,就不会这样。

其他回答

具有性能

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

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

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

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

process.hrtime()在Node.js中可用-它返回以纳秒为单位的值

let hrTime = process.hrtime()
console.log(hrTime[0] * 1000000 + hrTime[1] / 1000)
export default class Singleton {

  static myInstance: Singleton = null;

  _timers: any = {};

  /**
   * @returns {Singleton}
   */
  static getInstance() {
    if (Singleton.myInstance == null) {
      Singleton.myInstance = new Singleton();
    }

    return this.myInstance;
  }

  initTime(label: string) {
    this._timers[label] = Date.now();
    return this._timers[label];
  }

  endTime(label: string) {
    const endTime = Date.now();
    if (this._timers[label]) {
      const delta = endTime - this._timers[label];
      const finalTime = `${label}: ${delta}ms`;
      delete this._timers[label];
      return finalTime;
    } else {
      return null;
    }
  }
}

与字符串相关的InitTime。

return Singleton.getInstance().initTime(标签);//返回时间init

return Singleton.getInstance().endTime(标签);//返回初始化和结束之间的总时间