PHP profiling with microtime(): Negative time?
Asked Answered
U

1

43

For a very simple profiling I use microtime() like this:

$now = microtime();
for (...) {
    // do something
    echo microtime() - $now;
    $now = microtime();
}

Now, the output of the echo line seems completely random, that is, I expected fluctuations, but I didn't expect negative numbers showing up.

However, a typical result contains ~ 1/3 negative numbers. I confirmed this on Solaris (PHP 5.0.x) and WinVista (PHP 5.2.3).

What the heck is going on here? Have I invented accidently a time machine?

Unsphere answered 9/4, 2010 at 11:58 Comment(2)
Yes U have!!!!! :) Let me know to control it....Copt
this is something i noticed too but never bothered investigating, i'm curious for the anwser :)Coccyx
M
70

If you want to do operations on what is returned by microtime, you have to set the "get as float" parameter to true (it defaults to false).

http://www.php.net/manual/en/function.microtime.php

$now = microtime(true);
for (...) {
    // do something
    echo microtime(true) - $now;
    $now = microtime(true);
}
Magdalen answered 9/4, 2010 at 12:2 Comment(2)
Yes, yes. Reading the documentation sometimes helps. Thanks for the answer!Unsphere
To complete Arkh's answer: The response of microtime() without get_as_float is the string sprintf('%f %d', $microseconds, time()). Under what circumstances will anyone ever need this representation?Unsphere

© 2022 - 2024 — McMap. All rights reserved.