0

使用 Date 对象计算特定代码的速度是否正确?

var start = +new Date(); //get start time

    /*
     *    
     *    all the commands here
     *
     */

var stop = +new Date(); //get stop time
console.log(stop - start);

还是有另一种更好的方法来获得结果。我想这种方式非常受您在哪个浏览器上测试等等的影响......

4

4 回答 4

3

好吧,一般来说是的,如果您正在绘画,您还可以考虑粗略的绘画时间:

var start = +new Date();

//Do dom methods draw to canvas etc

setTimeout( function() {
   var stop = +new Date();
   console.log( stop - start - 13 );
}, 13 );

此外,请确保将每个测试作为函数调用,并在对函数计时之前对函数进行预热,而不是直接执行代码。

function test1() {
    //ops
}

function test2() {
    //ops
}
var l = 1e5;
while (l--) {
    //warmup
    test1();
    test2();
}
var start = +new Date();
var l = 1e5;

while (l--) {
    test1();
}

var stop = +new Date();
console.log(stop - start);


var start = +new Date();
var l = 1e5;

while (l--) {
    test2();
}

var stop = +new Date();
console.log(stop - start);

您应该注意,此设置会引入 JIT 优化(这就是它首先完成的原因),因此您应该注意消除死代码。

于 2013-06-26T15:10:34.923 回答
2

更好地使用控制台计时器:https ://developer.mozilla.org/en-US/docs/Web/API/console

console.time("answer time");
alert("Click to continue");
console.timeEnd("answer time");
于 2013-06-26T15:12:03.897 回答
1

是的,有更好的方法,检查一下What is the best way to profile javascript execution?

基本上:

console.profile([title])
...
console.trace()
...
console.profileEnd ()
于 2013-06-26T15:12:49.210 回答
1

如果您使用 Firefox,这里有一个替代解决方案:您可以使用分析器来了解您的 javascript 运行所需的确切时间。

如何使用它(快速方式):
1)通过在 Firefox 中按 shift-f5 来调出分析器。
2) 开始分析并重新加载您的网页
3) 停止分析,然后它应该加载分析数据
4) 展开小箭头,看起来像 : "> (total)",它将显示所有在运行期间运行的脚本页面加载,按执行时间排序(以毫秒为单位)
5)找到你的脚本,时间在工具的左侧,以毫秒表示。

于 2013-06-26T15:14:48.330 回答