2015-10-13 119 views
1

我已經使用microtime()來檢查代碼的執行時間。 但似乎很奇怪,像跟蹤的時間不正確。PHP microtime()是否正確?

在我的test.php的

所以,我有這樣的代碼如下:

$debug = true; 
$start = microtime(true); 
$newline = "<br/>"; 

... 

if ($debug) { 
    $time_elapsed_secs = microtime(true) - $start; 
    $start = microtime(true); 
    echo 'Step 1 Done: ' . $time_elapsed_secs . $newline; } 

... 

if ($debug) { 
    $time_elapsed_secs = microtime(true) - $start; 
    $start = microtime(true); 
    echo 'Step 2 Done: ' . $time_elapsed_secs . $newline; } 

後來,當我打開瀏覽器的URL,它在不到1秒, 反應,但它顯示了像 一些奇怪的值步驟1完成:0.0026565 步驟2完成:9.8646454

這是怎麼發生的? 我做錯了什麼嗎?

+0

「完成第1步:0.0026565」 的意思,它採取0.0026565秒得到這一點。 「第2步完成:9.8646454」意味着它花費了9.8646454秒才能到達該點。 – samlev

回答

1

我猜你在描述中留下了一個小細節。我認爲你實際看到的輸出更像是...

Step 1 Done: 0.0026565 
... 
Step 2 Done: 9.8646454E-5 

當PHP低於0.0001時,它會將浮點數轉換爲科學記數法。要使輸出中的內容一致,請嘗試將代碼更改爲以下格式,以十進制格式顯示microtimes。

$debug = true; 
$start = microtime(true); 
$newline = "<br/>"; 

usleep(30); 

if ($debug) { 
    $time_elapsed_secs = microtime(true) - $start; 
    $start = microtime(true); 
    echo 'Step 1 Done: ' . sprintf('%f', $time_elapsed_secs) . $newline; } 

usleep(1); 

if ($debug) { 
    $time_elapsed_secs = microtime(true) - $start; 
    $start = microtime(true); 
    echo 'Step 2 Done: ' . sprintf('%f', $time_elapsed_secs) . $newline; } 

[注:加usleep()函式呼叫顯示出事。]

+0

是的,你是對的,我錯過了。 :-) – Codemole

1

這取決於兩步之間的代碼是什麼。註釋掉兩個步驟之間的代碼(但是你是對的很奇怪,如果頁面返回的值小於1秒。)

// Sleep for a while 
usleep(100); 

檢查microtime中測量正確的時間差。

+0

是我的錯誤,不正確地檢查值。 :-) – Codemole