Javascript benchmarking couldn’t be easier. With this webpage you can input any Javascript code and test how fast it is. The webpage will automatically call your code for 1,000,000 iterations and report the total amount of time that it took to execute. It will even output a variable that you can use for debugging. You can now test an algorithm, make a modification, and test again to see if the modification helped the execution time.
Click here to benchmark some code.
When you visit the page it’ll show you some sample code that you can run. The number of iterations will default to 1,000,000 for all browsers except IE (100,000 for IE). You can change the code to your own algorithm and run the benchmark.
As soon as you press the button, a cookie will be created to store what you entered. At any time you can come back to the webpage and continue your testing with the code that you entered last.
The page includes jQuery 1.7.1, so you can be confident in using jQuery functions. It also includes setCookie and getCookie functions if you wanted to work with cookies. Instead of using the eval() function, which is considered bad practice in Javascript, the webpage sets your code to a new Function object. This improves the speed considerably at runtime.
The Code
//Pads a number to 2 decimal places
function pad2(number) {
return (number < 10 ? '0' : '') + number
}
//An output variable that you can use.
var out = "";
//Does the work
function startBenchmark(){
out = "";
var SB_iterations;
var SB_results = document.getElementById("results");
var SB_code = document.getElementById("code").value;
setCookie("code",escape(SB_code),365);
//test iterations for incorrect value
if((SB_iterations = parseInt(document.getElementById("iterations").value,10)) == 'NaN'){
SB_results.innerHTML = '<span style="color:red;font-weight:bold;">Error: The iterations must be a whole number such as 100000. Do not use commas or words.</span>';
return false;
}
//check for blank code
if(SB_code == ''){
SB_results.innerHTML = '<span style="color:red;font-weight:bold;">Error: You must type some code into the text area.</span>';
return false;
}
//too slow
/*var fn = function() {
window.eval.call(window,SB_code);
};*/
//better method
var fn = new Function(SB_code);
var SB_start = (new Date).getTime();
/* Run a test. */
for(var SB_i=0; SB_i < SB_iterations; SB_i++){
fn();
}
var SB_diff = (new Date).getTime() - SB_start;
var seconds = Math.floor((SB_diff/1000)%60);
var minutes = Math.floor((SB_diff/(1000*60))%60);
var ms = SB_diff - (minutes*60*1000) - (seconds*1000);
SB_results.innerHTML = "<p>Runtime: "+SB_diff+"ms<br />"+
pad2(minutes)+":"+pad2(seconds)+":"+pad2(ms)+" (mm:ss:ms)</p>"+
(out != ''?'<p><span class="bold">Output Variable:</span> '+out+'</p>':'');
}