2013-10-24 53 views
3

使用下面的腳本計算執行時間:PHP計算的執行時間,有時返回負值

$ 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 

爲什麼時間計算有時返回負值?

回答

5

傳遞的第二個參數:

microtime(true); 

否則,你得到一個字符串,而不是導致意外/錯誤的結果一個真正的浮點值:

默認情況下,microtime中()返回形式的字符串「毫秒秒」,其中 秒是因爲 Unix紀元中的秒數測量的當前時間(0時00分00秒1970年1月1日GMT),以及毫秒錶示0數從秒開始經過的秒數以秒爲單位的微秒。

php.net/microtime

(重點煤礦)

例子:

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

瀏覽器訪問該網站時警告我網站的安全隱患?你有這個嗎? https://www.google.co.uk/interstitial?url=http://php.net/ –

+0

@ScottHelme這很奇怪。我沒有看到它,只有當點擊你的鏈接。 – ComFreek

+0

是的,這是它帶我到的頁面。您是否使用Chrome瀏覽器? –