I've seen several questions on this topic, all with the same basic answer. Use microtime() to record the start and end time, then subtract. Mostly this works, except when the event spans the point where the seconds are incremented. At that point the end time may be less than the start time.
Can you use a function to add seconds to the microtime() to get seconds + microtime?
Example:
function getSMtime() {
return time() + (microtime() / 1000000);
}
$start = getSMtime();
... some code to be timed ...
$end = getSMtime();
echo "Time elapsed: " . ($end - $start) . " seconds.";
You should provide the argument true
to get a float as result, not a string:
microtime(true)
From the documentation:
By default,
microtime()
returns a string in the form "msec sec", where sec is the number of seconds since the Unix epoch (0:00:00 January 1,1970 GMT), and msec measures microseconds that have elapsed since sec and is also expressed in seconds.If
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.
As a consequence, if you don't provide this argument, the return value will be a string like:
0.65538700 1481746900
...where the first part is always a value between 0 and 1. If you divide that result string by 1000000 like you do, then a implicit conversion to a number happens whereby the second part of the string is ignored. So indeed, you only get to calculate with the microsecond part of the timestamp then.
Conclusion: use the true
argument.