doumeikuan6834 2014-05-26 12:00
浏览 24
已采纳

PHP microtime()精度(最后为零)

I've got two "similar" questions about microtime accuracy.


1) As was suggested in PHP online documentation, to get time in microseconds, I'm using a following code with microtime() function (looped):

<?php
    for ($i = 0; $i < 10; $i++) {
        list($usec, $sec) = explode(' ', microtime()); //split the microtime on space
        $usec = str_replace('0.', ' ', $usec); // remove the leading '0.' from usec
        echo date('YmdHis', $sec) .' '. $usec ."<br>"; 
    }
?>

I'm getting following results:

20140526135144 72254300
20140526135144 72255900
20140526135144 72256500
20140526135144 72257100
20140526135144 72257600
20140526135144 72258100
20140526135144 72258600
20140526135144 72259100
20140526135144 72259600
20140526135144 72260100

Micro means 1/100000 as far as I'm concerned. So why does microtime return 8 integers for "micro" part, and the last two are always zeros? Or I should play some lottery because I'm so happy :)?


2) Microtime is sometimes used to generate uniqid for example. But when I run:

for ($i = 0; $i < 10; $i++) {
    echo microtime()."<br>";
}

I'm getting:

0.21820300 1401105400
0.21821000 1401105400
0.21821100 1401105400
0.21821200 1401105400
0.21821300 1401105400
0.21821300 1401105400 // - the same as precursor
0.21821400 1401105400
0.21821500 1401105400
0.21821500 1401105400 // - the same as precursor
0.21821600 1401105400

How is that possible? My computer is not that fast as newer one. Is this dangerous? BTW I'm using additional "br" output, which makes the code run slower :P.


UPDATE According to comments, this is microdate(true).

1401106486.9772
1401106486.9772
1401106486.9772
1401106486.9772
1401106486.9772
1401106486.9772
1401106486.9772
1401106486.9772
1401106486.9772
1401106486.9772

To cite Zorba the Greek: Total catastrophy!

  • 写回答

2条回答 默认 最新

  • dongzengzai4567 2014-05-26 12:44
    关注

    I think you should refer to the answer to this question DECIMAL length for microtime(true)? .

    Basically microtime makes a system call and is therefore system dependant with a precision limited by the hardware.

    As for the security issue, you should not use microtime as a unique id. Have a look at http://www.php.net/manual/en/function.uniqid.php and try to use it with the more_entropy flag.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 luckysheet
  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题