Profiler


Algorithms to test:

function test1() {
  for (var i=0;i<10000;i++) {
    var j = i*i;
  };
};

function test2() {
  for (var i=10000;i--;) {
    var j = i*i;
  };
};

function test3 () {
  var i = 10000;
  
  while (i--) {
    var j = i*i;
  }
};

How we invoke profiler:

var results = profiler(test1, test2, test3);

How we can show the results:

alert(results[0].id + " was the fastest"); // "2 was the fastest"
alert(results); // "2:1,  1:4, 3:6"(2nd function took 1ms, etc.)

Ever had two algorithms and wondered which one was the quickest?

Profiler is a quick function I made which accepts an unlimited number of functions as parameters. It runs each one a number of times before telling you which was the fastest.

Note that tools such as Firebug provide much better methods of profiling your code, however it is only available in Mozilla Firefox.

To use profiler, simply invoke `profiler`, and pass each algorithm you wish to test, wrapped in a function, as a parameter. To give a fair test, each algorithm is run a number of times. To change the default value, provide a number as the final parameter. Profiler returns an array of results, ordered by the time taken in ascending order. Each result is an object with the fields id, which was the the position of the algorithm in the arguments array, and val, which was the time taken to execute the algorithm. As these objects have a custom toString method, you can alert the returned value immediately.

Download or view the code