使用下面的脚本计算执行时间:
$ 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.
(强调我的)
例子:
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/