Is there a package that helps me benchmark JS code ? Im not referring the Firebug and such tools.
I need to compare 2 different JS functions that I have implemented. Im very familiar with perl's Benchmark ( http://search.cpan.org/~tty/kurila-1.19_0/lib/Benchmark.pm ) module and Im looking for something similar in javascript.
Is the emphasis on benchmarking the JS code overboard ? Can I get away with timing just one run of the functions ?
Source: Tips4all
Just time several iterations of each function. One iteration probably won't be enough, but (depending on how complex your functions are) somewhere closer to 100 or even 1,000 iterations should do the job.
ReplyDeleteFirebug also has a profiler if you want to see which parts of your function are slowing it down.
I'd start with http://jsperf.com . It works well for testing code that can easily be copy-pasted into the UI there.
ReplyDeleteIf you need more control over the setup (i.e. you want to provide lots of markup and/or import scripts), you can try my JSLitmus script:
http://www.broofa.com/Tools/JSLitmus/
The latest version (designed to provide more API and less UI) can be found here:
https://github.com/broofa/jslitmus
I have been using this simple implementation of @musicfreaks answer. There are no features, but it is really easy to use. This bench(function(){return 1/2;}, 10000, [], this) will calculate 1/2 10,000 times.
ReplyDelete/**
* Figure out how long it takes for a method to execute.
*
* @param {func} method to test
* @param {int} iterations number of executions.
* @param {Array} args to pass in.
* @param {T} context the context to call the method in.
* @return {int} the time it took, in milliseconds to execute.
*/
var bench = function (method, iterations, args, context) {
var time = 0;
var timer = function (action) {
var d = +(new Date);
if (time < 1 || action === 'start') {
time = d;
return 0;
} else if (action === 'stop') {
var t = d - time;
time = 0;
return t;
} else {
return d - time;
}
};
var result = [];
var i = 0;
timer('start');
while (i < iterations) {
result.push(method.apply(context, args));
i++;
}
var execTime = timer('stop');
if ( typeof console === "object") {
console.log("Mean execution time was: ", execTime / iterations);
console.log("Sum execution time was: ", execTime);
console.log("Result of the method call was:", result[0]);
}
return execTime;
};
It’s really hard to write decent cross-browser benchmarks. Simply timing a pre-defined number of iterations of your code is not bulletproof at all.
ReplyDeleteAs @broofa already suggested, check out jsPerf. It uses Benchmark.js behind the scenes.
if writing a custom benchmark script be sure to note that some browsers apply dom manipulations only after function in which they are defined is ended. More details here
ReplyDeletehttp://www.quirksmode.org/blog/archives/2009/08/when_to_read_ou.html