[php] Accurate way to measure execution times of php scripts

You can use REQUEST_TIME from the $_SERVER superglobal array. From the documentation:

REQUEST_TIME
The timestamp of the start of the request. (Available since PHP 5.1.0.)

REQUEST_TIME_FLOAT
The timestamp of the start of the request, with microsecond precision. (Available since PHP 5.4.0.)

This way you don't need to save a timestamp at the beginning of your script. You can simply do:

<?php
// Do stuff
usleep(mt_rand(100, 10000));

// At the end of your script
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];

echo "Did stuff in $time seconds\n";
?>

Here, $time would contain the time elapsed since the start of the script in seconds, with microseconds precision (eg. 1.341 for 1 second and 341 microseconds)


More info:

PHP documentation: $_SERVER variables and microtime function