7

Not really, but I am running into an issue where once in a blue moon while running this script, my time results in a negative number. here is the part of the script where it is happening:

public function execute()
{
    $time1 = microtime();
    foreach($this->tables as $table)
    {
        if($this->buildQuery($table))
        {
            if($this->submitQuery($table))
            {
                $time2 = microtime() - $time1;
                echo "Sync Successful({$time2}s).. $table <br /> \n";
                //log
            }
        }
        else echo "No data to sync in $table";
    }    
}

As you would suspect.. there should be nothing wrong with subtracting second time from the first and getting a rough estimate of how long the process took.. However.. If I run it enough times, sometimes the results will print out the following:

Sync Successful(0.062936s).. users
Sync Successful(-0.86901s).. profile
Sync Successful(-0.798774s).. groups
Sync Successful(-0.718851s).. phonebook
Sync Successful(-0.711768s).. products
No data to sync in locations

This is very rare, but this is an exact output of my last result. So my questions would be:

How is this possible? resulting in a 'negative' when this should clearly should not happen..

What can I do to avoid this? Is there a better way to go about this? Is microtime() unreliable?

Can someone lend me a 1981 DeLorean DMC-12 capable of 88 mp/h?

grep
  • 3,776
  • 7
  • 38
  • 66
  • 3
    possible duplicate of [PHP profiling with microtime(): Negative time?](http://stackoverflow.com/questions/2607150/php-profiling-with-microtime-negative-time) – lonesomeday Jul 14 '11 at 17:20

1 Answers1

14

You’re assuming the wrong data type. The manual page of microtime reads:

By default, microtime() returns a string in the form "msec sec" […]

So you’re actually subtracting only the msec values as both strings are converted to numbers before the actual subtraction takes place.

Use microtime(true) to get float values:

If get_as_float is set to TRUE, then microtime() returns a float […]

Gumbo
  • 594,236
  • 102
  • 740
  • 814
  • 12
    One of those wonderful design decisions in PHP that really make the language such a joy to use. – Marc B Jul 14 '11 at 17:25