Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP script... goes back in time?

Tags:

php

microtime

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?

like image 563
grep Avatar asked Jul 14 '11 17:07

grep


1 Answers

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 […]

like image 113
Gumbo Avatar answered Oct 22 '22 01:10

Gumbo