+2 votes
in Programming Languages by (4.6k points)

How can I calculate the execution time of a PHP script?

E.g.

What is the time taken by the following code for execution?

<?php

$x = 1;

for($i=1; $i<=10; $i++){

    $x+=$x*$i;

}

?>

1 Answer

0 votes
by (21.4k points)

You can use microtime() that returns current Unix timestamp with microseconds. Use microtime() with parameter true to get float value instead of a string.

<?php
$time_start = microtime(true);

$x = 1;
for($i=1; $i<=10; $i++){
    $x+=$x*$i;
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Computed $x in $time seconds\n";
?>

When you run the above code, you should get the output as follows:

Computed 39916800 in 5.0067901611328E-6 seconds

...