如何测量函数执行所花费的时间

JavaScript

Tom神奇

2020-03-09

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

我最初在2008年问这个问题。当时接受的答案是使用new Date()。getTime()。但是,我们现在都可以同意使用标准performance.now() API更合适。因此,我正在更改对此答案的公认答案。

第345篇《如何测量函数执行所花费的时间》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

10个回答
蛋蛋L 2020.03.09
  1. 开始使用计时器console.time("myTimer");
  2. 可选:打印经过的时间,请使用 console.timeLog("myTimer");
  3. 最后,停止计时器并显示最终时间:console.timeEnd("myTimer");

You can read more about this on MDN and in the Node.js documentation.

Available on Chrome, Firefox, Opera and NodeJS. (not on Edge or Internet Explorer).

阿飞神乐 2020.03.09

就我而言,我倾向于使用@ 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"
    ]
 }
小哥达蒙 2020.03.09
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 string

return Singleton.getInstance().initTime(label); // Returns the time init

return Singleton.getInstance().endTime(label); // Returns the total time between init and end

神无十三 2020.03.09

谢谢,Achim Koellner,将扩大您的答案:

var t0 = process.hrtime();
//Start of code to measure

//End of code
var timeInMilliseconds = process.hrtime(t0)[1]/1000000; // dividing by 1000000 gives milliseconds from nanoseconds

请注意,除了要度量的内容外,您不应做其他任何事情(例如,console.log执行过程也会花费一些时间,并且会影响性​​能测试)。

注意,为了通过度量异步函数的执行时间,应该var timeInMilliseconds = process.hrtime(t0)[1]/1000000;在回调内部插入例如,

var t0 = process.hrtime();
someAsyncFunction(function(err, results) {
var timeInMilliseconds = process.hrtime(t0)[1]/1000000;

});
Gil伽罗小宇宙 2020.03.09

由于在某些主要浏览器(例如IE10)中不支持console.timeperformance.now,因此我创建了一个细长的实用程序,该实用程序利用了最佳的可用方法。但是,它缺乏对错误用法的错误处理(调用End()未初始化的计时器)。

使用它并根据需要对其进行改进。

Performance: {
    Timer: {},
    Start: function (name) {
        if (console && console.time) {
            console.time(name);
        } else if (window.performance.now) {
            this.Timer[name] = window.performance.now();
        } else {
            this.Timer[name] = new Date().getTime();
        }
    },
    End: function (name) {
        if (console && console.time) {
            console.timeEnd(name);
        } else {
            var result;
            if (window.performance.now) {
                result = window.performance.now() - this.Timer[name];
            } else {
                result = new Date().getTime() - this.Timer[name];
            }
            console.log(name + ": " + result);
        }
    }
}
逆天小哥蛋蛋 2020.03.09

它可能会帮助您。

var t0 = date.now(); doSomething(); var t1 = date.now(); console.log("Call to doSomething took approximate" + (t1 - t0)/1000 + " seconds.")

乐米亚 2020.03.09

只能使用一个变量:

var timer = -performance.now();

// Do something

timer += performance.now();
console.log("Time: " + (timer/1000).toFixed(5) + " sec.")

timer/1000 -将毫秒转换为秒

.toFixed(5) -修剪多余的数字

小胖Itachi西里 2020.03.09

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

达蒙A宝儿 2020.03.09

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

var hrTime = process.hrtime()
console.log(hrTime[0] * 1000000 + hrTime[1] / 1000)
路易Pro 2020.03.09

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android