如何在Javascript

时间:2017-07-07 07:32:44

标签: javascript optimization timing

不是How to measure time taken by a function to execute的副本。请在将其标记为其他内容的副本之前,先阅读我的问题。无论如何,它已被回答。

我有像

这样的代码
for (var i = 0 ; i < 10000 ; i++) {

    doSomething();

    doSomethingElse();

}

我想知道循环中的每个函数整体上花了多少时间。我该如何衡量?

2 个答案:

答案 0 :(得分:1)

var t1;
var t2;
var f1Time =0;
var f2Time =0;
for (var i = 0 ; i < 10000 ; i++) {
    t1 = performance.now();
    doSomething();
    t2  = performance.now();
    f1Time+= (t2 - t1);

    t1 = performance.now();
    doSomethingElse();
    t2  = performance.now();
    f1Time+=(t2 - t1);

}

答案 1 :(得分:0)

创建一个测试对象并注册各个时差:

&#13;
&#13;
function doSomething() {
  t = Date.now();
  while (Date.now() < t + 13) {}
}

function doSomethingElse() {
  t = Date.now();
  while (Date.now() < t + 27) {}
}
var tests = {
  "doSomething": [],
  "doSomethingElse": []
};
for (var i_1 = 0; i_1 < 10; i_1++) {
  var t = Date.now();
  doSomething();
  tests.doSomething.push(Date.now() - t);
  t = Date.now();
  doSomethingElse();
  tests.doSomethingElse.push(Date.now() - t);
}
for (var key in tests) {
  if (tests.hasOwnProperty(key)) {
    tests[key] = tests[key]
      .reduce(function(sum, value) {
        return sum + value;
      }, 0);
  }
}
console.log(tests);
&#13;
&#13;
&#13;