Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Benchmarking tool

Benchmarking

Benchmarking tool

by  jemminger  Posted    (Edited  )
sick of reinventing the wheel every time i wanted to performance benchmark some functions, i wrote a simple tool to do it for me... it executes your function and outputs the elapsed time in seconds that it took to run. output is written to a textarea with id "benchmark-output", which is created dynamically if it does not exist.

one thing to keep in mind: make sure to allow the document to load first before attempting to call benchmark(), since it will attempt to write to document.body

Code:
/**
 * @param fn, the function to execute
 * @param args, a single argument or an array
          of arguments expected by param "fn"
 * @param optionalDisplayName, an optional name to
          show in the benchmark output
 */
function benchmark(fn, args, optionalDisplayName) {
    var output = document.getElementById("benchmark-output");

    //  set up the output textarea
    if (!output) {
        var container = document.createElement("div");
        container.setAttribute("id", "benchmark-container");

        var title = document.createElement("div");
        title.setAttribute("id", "benchmark-title");
        title.appendChild( document.createTextNode("benchmark results") );

        output = document.createElement("textarea");
        output.setAttribute("id", "benchmark-output");
        output.style.width = "100%";
        output.style.height = "15em";

        container.appendChild(title);
        container.appendChild(output);

        document.body.appendChild(container);
    }

    // make sure args is an Array
    if (args && args.constructor != Array) args = [args];
    
    var iStart = new Date().getTime();
    fn.apply(this, args);
    var iStop = new Date().getTime();

    var name = optionalDisplayName || /(.+)\n/.exec(fn.toString())[1];
    output.value += name + " : " + ((iStop-iStart)/1000) + " sec\n";
}

[highlight]usage:[/highlight]
Code:
//  no args
function foo() {
  // do something
}

benchmark( foo );

//  with args
function bar1(arg) {
  // do something
}
function bar2(arg1, arg2, arg3) {
  // do something
}

benchmark( bar1, "something" );
benchmark( bar2, ["something", "2", "3"] );

//  using optional display name since functions defined
//  like below don't report a name
document.foobar = function(arg) {
  // do something
}

benchmark( document.foobar, "blah", "foobar()" );


_____________________________________________________________________________________________
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top