Accurate way to measure execution times of php scripts
You can use microtime(true)
with following manners:
Put this at the start of your php file:
//place this before any script you want to calculate time
$time_start = microtime(true);
// your script code goes here
// do something
Put this at the end of your php file:
// Display Script End time
$time_end = microtime(true);
//dividing with 60 will give the execution time in minutes other wise seconds
$execution_time = ($time_end - $time_start)/60;
//execution time of the script
echo '<b>Total Execution Time:</b> '.$execution_time.' Mins';
It will output you result in minutes
.
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
You can use the microtime
function for this. From the documentation:
microtime
— Return current Unix timestamp with microsecondsIf
get_as_float
is set toTRUE
, thenmicrotime()
returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.
Example usage:
$start = microtime(true);
while (...) {
}
$time_elapsed_secs = microtime(true) - $start;