Skip to content

Instantly share code, notes, and snippets.

@michealbenedict
Created May 19, 2011 12:52
Show Gist options
  • Save michealbenedict/980677 to your computer and use it in GitHub Desktop.
Save michealbenedict/980677 to your computer and use it in GitHub Desktop.
JS Benchmarking (John Resig)
// T-Distribution
var tDistribution = 2.776;
// Run the tests in order
runTest("Max Runs, Simple Test", test1, function(){
});
// Run the V8-style Max test (but with error determination)
function runTest(name, test, next){
var runs = [], r = 0;
setTimeout(function(){
var start = (new Date).getTime(), diff = 0;
for ( var n = 0; diff < 1000; n++ ) {
test();
diff = (new Date).getTime() - start;
}
runs.push( n );
if ( r++ < 4 )
setTimeout( arguments.callee, 0 );
else {
done(name, runs);
if ( next )
setTimeout( next, 0 );
}
}, 0);
}
// Run the SunSpider/Dromaeo style of test execution
function runTest2(name, test, num, next){
var runs = [], r = 0;
setTimeout(function(){
var start = (new Date).getTime();
test();
runs.push( (new Date).getTime() - start );
if ( ++r < num )
setTimeout( arguments.callee, 0 );
else {
done(name, runs);
if ( next )
setTimeout( next, 0 );
}
}, 0);
}
// Calculate all the details from the resulting numbers
function compute(times, runs){
var num = times.length, results = {runs: num};
times = times.sort(function(a,b){
return a - b;
});
// Make Sum
results.sum = 0;
for ( var i = 0; i < num; i++ )
results.sum += times[i];
// Make Min
results.min = times[0];
// Make Max
results.max = times[ num - 1 ];
// Make Mean
results.mean = results.sum / num;
var log = 0;
for ( var i = 0; i < num; i++ ) {
log += Math.log(times[i]);
}
results.geometric_mean = Math.pow(Math.E, log / num);
// Make Median
results.median = num % 2 == 0 ?
(times[Math.floor(num/2)] + times[Math.ceil(num/2)]) / 2 :
times[Math.round(num/2)];
// Make Variance
results.variance = 0;
for ( var i = 0; i < num; i++ )
results.variance += Math.pow(times[i] - results.mean, 2);
results.variance /= num - 1;
// Make Standard Deviation
results.deviation = Math.sqrt( results.variance );
// Compute Standard Errors Mean
results.sem = (results.deviation / Math.sqrt(results.runs)) * tDistribution;
// Error
results.error = ((results.sem / results.mean) * 100) || 0;
return results;
}
function test1(){
$("#jq-siteLogo");
}
// Output the results
function done(name, runs){
var results = compute(runs), str = "\n\n" + name + "\n----------------------------\n";
for ( var i in results ) {
str += i + ":\t\t" + results[i] + "\n";
}
console.log(str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment