Question

Calculating execution time using script below:

$ php -r "\$tt=microtime();for(\$i=0;\$i<111120;\$i++) \
  echo hash('crc32', microtime()).PHP_EOL;echo 'Time took: ' \
   . (microtime()-\$tt).PHP_EOL;"

Results (multiple):

...
Time took: 0.266269
...
Time took: -0.725037
...
Time took: 0.264577
...
Time took: 0.655573
...
Time took: -0.389367
...
Time took: -0.451503
...
Time took: 0.50867

Why time calculation some times returns negative value?

Was it helpful?

Solution

Pass the second parameter:

microtime(true);

Otherwise you get a string instead of a real float value which leads to unexpected/wrong results:

By default, microtime() returns a string in the form "msec sec", where sec is the current time measured in the number of seconds since the Unix epoch (0:00:00 January 1, 1970 GMT), and msec is the number of microseconds that have elapsed since sec expressed in seconds.

php.net/microtime

(Emphasis mine)

Examples:

microtime():     0.93146600 1382611111   (string value)
microtime(true): 1382611111.93146600     (float, printed as a string in this case)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top