I thought I'd share the function I put together. Hopefully it can save you time.
It was originally used to track timing of a text-based script, so the output is in text form. But you can easily modify it to HTML if you prefer.
It will do all the calculations for you for how much time has been spent since the start of the script and in each step. It formats all the output with 3 decimals of precision. (Down to milliseconds.)
Once you copy it to the top of your script, all you do is put the recordTime function calls after each piece you want to time.
Copy this to the top of your script file:
$tRecordStart = microtime(true);
header("Content-Type: text/plain");
recordTime("Start");
function recordTime ($sName) {
global $tRecordStart;
static $tStartQ;
$tS = microtime(true);
$tElapsedSecs = $tS - $tRecordStart;
$tElapsedSecsQ = $tS - $tStartQ;
$sElapsedSecs = str_pad(number_format($tElapsedSecs, 3), 10, " ", STR_PAD_LEFT);
$sElapsedSecsQ = number_format($tElapsedSecsQ, 3);
echo "//".$sElapsedSecs." - ".$sName;
if (!empty($tStartQ)) echo " In ".$sElapsedSecsQ."s";
echo "\n";
$tStartQ = $tS;
}
To track the time that passes, just do:
recordTime("What We Just Did")
For example:
recordTime("Something Else")
//Do really long operation.
recordTime("Really Long Operation")
//Do a short operation.
recordTime("A Short Operation")
//In a while loop.
for ($i = 0; $i < 300; $i ++) {
recordTime("Loop Cycle ".$i)
}
Gives output like this:
// 0.000 - Start
// 0.001 - Something Else In 0.001s
// 10.779 - Really Long Operation In 10.778s
// 11.986 - A Short Operation In 1.207s
// 11.987 - Loop Cycle 0 In 0.001s
// 11.987 - Loop Cycle 1 In 0.000s
...
// 12.007 - Loop Cycle 299 In 0.000s
Hope this helps someone!