Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I measure the execution time of a script? [duplicate]

Tags:

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

 start-timing
   //CODE
 end-timing
like image 973
Skizit Avatar asked Jan 24 '11 17:01

Skizit


People also ask

How do you measure time in a script?

To calculate script execution time use clock time rather than the CPU execution time. Knowing clock time before script execution and after script execution will help to know the script execution time. Clock time can get using microtime() function. First use it before starts the script and then at the end of the script.

How is execution time calculated?

1) Create a loop around whatneeds to be measured, that executes 10, 100, or 1000 times or more. Measure execution time to the nearest 10 msec. Then divide that time bythe number of times the loop executed. If the loop executed 1000 timesusing a 10 msec clock, you obtain a resolution of 10 µsec for theloop.

How does PHP calculate time of execution?

Use PHP's microtime() function to measure script execution time. Make more performant decisions with your application.


1 Answers

EDIT: in January 2011, this was the best available solution. Other solutions (such as performance.now() 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();
    script();
    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 :

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

console.profile('profile1');
    // CODE
console.profileEnd('profile1'); // this prints usual profiling informations, per function, etc.
like image 111
Arnaud Le Blanc Avatar answered Sep 20 '22 06:09

Arnaud Le Blanc