Skizit Skizit - 5 months ago 8x
Javascript Question

How can I measure the execution time of a script?

How would I measure the time it takes for a script to run from start to finish?



EDIT: in January 2011, this was the best available solution. Other solutions (such as should be preferred now.

var start = new Date();
    // CODE
var time = new Date() - start;
// time is the number of milliseconds it taken to execute the script

You may also want to wrap that in a function:

function time_my_script(script) {
    var start = new Date();
    return new Date() - start;

// call it like this:
time = time_my_script(function() {
    // CODE

// or just like this:
time = time_my_script(func);

If you are trying to profile your code, you may want to try the Firebug extension, which includes a javascript profiler. It has a great user interface for profiling, but it also can be done programmatically with its console api :

    // CODE
console.timeEnd('timer1'); // this prints times on the console

    // CODE
console.profileEnd('profile1'); // this prints usual profiling informations, per function, etc.