Javascript:在线测量代码执行时间

Javascript: measure code execution time online

本文关键字:代码 执行时间 测量 在线 Javascript      更新时间:2023-09-26

我需要测试一些代码变体(本机代码/插件代码)的性能差异。

有没有一个在线服务,比如用于执行的jsbin、jsfiddle,我可以在其中放入代码,像

// BEGIN
var bla;
jQuery.map(bla, function(){});
// END

并获得执行时间?

一个选项是

jsperf.com

//works in chrome and firefox
console.time("myCode"); // 'myCode' is the namespace
//execute your code here
console.timeEnd("myCode");

var startTime = window.performance.now();
//execute your code here
console.log(window.performance.now() - startTime);

使用"用户计时API"是一种现代的方法:
http://www.html5rocks.com/en/tutorials/webperformance/usertiming/

到目前为止,我发现了以下方法:-

方法1:-

let start = window.performance.now()
/// Your code goes here
let end = window.performance.now()
console.log(`Component Persing Time: ${end - start} ms`);

方法2:-

let start = Date.now()
/// Your code goes here
let end = Date.now()
console.log(`Component Persing Time: ${end - start} ms`);

方法3:-

console.time();
// Your code goes here
console.timeEnd();

您可以继续执行上述任何方法,但会得到相同的结果。快乐编码。:)

var startTime = Date.now();
// code ...
console.log("Elapsed time (ms): " + (Date.now() - startTime));