Description:
Detect how long a script, query or function takes to run in php.
Solution:
PHP offers the microtime() function, which returns the number of microseconds (a millionth of a second) that passed since 1st of January 1970, the PHP epoch.
The way to use it is assigning the microtime() value to a variable before the desired script and then one after, the difference between them being the result we need.
$time_start = microtime();
$run_function = processData();
$time_end = microtime();
$time = $time_end – $time_start;
echo “processData function completed in “.$time.” microseconds”;
Also we can multiply the result by 1 000 000 to get the number of seconds, or manipulate it as we wish, to return the result in any time related way:
echo date(“H:i:s”,$time);
This only works if you pass TRUE as first parameter, to microtime():
Example:
$time_start = microtime(true);
sleep(5);
$time_end = microtime(true);
$time = $time_end – $time_start;
echo “processData function completed in {$time} microseconds”;
Without passing true the results are not correct, because they microtime returns a string instead of a double (which you get when you pass true as the first parameter to microtime)
http://www.php.net//manual/en/function.microtime.php
True! Thanks for the correction
It gives time difference in seconds not milliseconds.