CPU周期,内存使用情况,执行时间等等?
除了感知代码的运行速度之外,是否有一种量化的方法来测试JavaScript的性能?
CPU周期,内存使用情况,执行时间等等?
除了感知代码的运行速度之外,是否有一种量化的方法来测试JavaScript的性能?
当前回答
我同意,感知到的表现真的是最重要的。但有时我只是想知道哪种方法做某事更快。有时这种差异是巨大的,值得了解。
你可以使用javascript计时器。但我通常会得到更一致的结果使用本机Chrome(现在也在Firefox和Safari) devTool方法console.time() & console.timeEnd()
我如何使用它的例子:
var iterations = 1000000;
console.time('Function #1');
for(var i = 0; i < iterations; i++ ){
functionOne();
};
console.timeEnd('Function #1')
console.time('Function #2');
for(var i = 0; i < iterations; i++ ){
functionTwo();
};
console.timeEnd('Function #2')
更新(4/4/2016):
Chrome金丝雀最近增加了行级别剖析开发工具的来源选项卡,让你看到每一行执行了多长时间!
其他回答
黄金法则是在任何情况下都不要锁定用户的浏览器。在此之后,我通常会查看执行时间,然后是内存使用情况(除非您正在做一些疯狂的事情,在这种情况下,内存使用的优先级可能更高)。
您可以使用https://github.com/anywhichway/benchtest,它用性能测试包装了现有的Mocha单元测试。
下面是一个简单的函数,显示传入函数的执行时间:
var perf = function(testName, fn) {
var startTime = new Date().getTime();
fn();
var endTime = new Date().getTime();
console.log(testName + ": " + (endTime - startTime) + "ms");
}
下面是一个用于时间性能的可重用类。示例包含在代码中:
/*
Help track time lapse - tells you the time difference between each "check()" and since the "start()"
*/
var TimeCapture = function () {
var start = new Date().getTime();
var last = start;
var now = start;
this.start = function () {
start = new Date().getTime();
};
this.check = function (message) {
now = (new Date().getTime());
console.log(message, 'START:', now - start, 'LAST:', now - last);
last = now;
};
};
//Example:
var time = new TimeCapture();
//begin tracking time
time.start();
//...do stuff
time.check('say something here')//look at your console for output
//..do more stuff
time.check('say something else')//look at your console for output
//..do more stuff
time.check('say something else one more time')//look at your console for output
我发现执行时间是最好的衡量标准。