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

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


当前回答

在我的例子中,我更喜欢使用@grammar suger并用babel编译它。这种方法的问题是函数必须位于对象内部。

JS代码示例

function timer() {
    return (target, propertyKey, descriptor) => {
        const start = Date.now();
        let oldFunc = descriptor.value;

        descriptor.value = async function (){
            var result = await oldFunc.apply(this, arguments);
            console.log(Date.now() - start);
            return result;
        }
    }
}

// Util function 
function delay(timeout) {
    return new Promise((resolve) => setTimeout(() => {
        resolve();
    }, timeout));
}

class Test {
    @timer()
    async test(timout) {
        await delay(timout)
        console.log("delay 1");
        await delay(timout)
        console.log("delay 2");
    }
}

const t = new Test();
t.test(1000)
t.test(100)

babelrc(用于babel 6)

 {
    "plugins": [
        "transform-decorators-legacy"
    ]
 }

其他回答

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(标签);//返回初始化和结束之间的总时间

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

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

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

使用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()比一元+运算符提供更好的性能。

支持标记的基本TypeScript示例。调用start(“something”)将启动计时器,而stop(“somehing”)将结束计时器,并返回包含已用时间的格式化字符串。

查看车队示例

/**
 * Mark entries
 */
export const marks: { [id: string]: number } = {};

/**
 * Start timing 
 */
export const start = (id: string) => {
  return Object.assign(marks, {[id]: Date.now() })[id]
}

/**
 * Clear all 
 */
export const clear = () => {
  for (const id in marks) delete marks[id]; 
};

/**
 * Stop timing and return formatted elapsed time
 */
export const stop = (id: string) => {
  const ms = Date.now() - marks[id];
  delete marks[id];
  return ms > 1000 
    ? `${(ms / 1000).toFixed(0)}s ${+ms.toFixed(0).slice(1)}ms` 
    : `${ms.toFixed(0)}ms`;
};

示例代码是导出每个函数。您可以将其放置到项目中,并从默认的import调用相应的方法,例如:

import * as time from './timer.js'

time.start('foo')

// do something

console.log('elapsed time: ' + time.stop('bar'))

使用Firebug,同时启用Console和Javascript。单击配置文件。重新加载再次单击配置文件。查看报告。