notes on javascript, linux, and more

3.27.2009

Simple Javascript Benchmarking Class

var Benchmark = function( testee, iterations ) {
var _Benchmark = this;
_Benchmark.testee = testee;
_Benchmark.iterations = iterations || 1;
_Benchmark.time = -1;
_Benchmark.runtime = -1;

_Benchmark.run = function() {
var time = 0;
for (var i=0; i<_Benchmark.iterations; i++) {
var startTime = new Date();
_Benchmark.testee();
var endTime = new Date();
time += endTime - startTime;
}
_Benchmark.runtime = time;
_Benchmark.time = time / iterations;
};
}


How to use it:
function nothing(x) {
// does a bunch of nothing
if (x > 0)
var y = (Math.sqrt(x) * Math.sqrt(nothing(x - 1)));
}

var myBenchmark = new Benchmark(function(){nothing(10)}, 300);
myBenchmark.run();
alert("Average run time to do nothing: " + myBenchmark.time );

No comments:

About Me

My photo
chicago, il, United States
I'm a software engineer by profession.

Labels