PHP计算执行时间,有时返回负值

标签 php time calculus

使用下面的脚本计算执行时间:

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

结果(多个):

...
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

为什么时间计算有时会返回负值?

最佳答案

传递第二个参数:

microtime(true);

否则你会得到一个字符串而不是一个真正的浮点值,这会导致意想不到的/错误的结果:

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

(强调我的)

例子:

microtime():     0.93146600 1382611111   (string value)
microtime(true): 1382611111.93146600     (float, printed as a string in this case)

关于PHP计算执行时间,有时返回负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19563575/

相关文章:

php - 如何创建带有毫秒的Mysql unix_timestamp

javascript - ajax转json

date - 如何将微秒转换为时间戳?

algorithm - 计算离散曲线下面积的复杂性

c++ - 计算两个函数的重叠面积

php - PHPDoc 中严格类型实体的提示迭代器

php - 为什么 PHP 需要递归存储相同的全局数据?

Jquery 时间微调器简化

c++ - C++ 中的多线程程序显示出与串行程序相同的性能

c++ - 是否有一种方法可以根据不同的变量重新计算和方程式?