我想知道環一個PHP需要多少毫秒執行。衡量PHP腳本的執行時間準確地
我知道一個通用算法的結構,但不知道如何實現它在PHP:
Begin
init1 = timer(); // where timer() is the amount of milliseconds from midnight
the loop begin
some code
the loop end
total = timer() - init1;
End
我想知道環一個PHP需要多少毫秒執行。衡量PHP腳本的執行時間準確地
我知道一個通用算法的結構,但不知道如何實現它在PHP:
Begin
init1 = timer(); // where timer() is the amount of milliseconds from midnight
the loop begin
some code
the loop end
total = timer() - init1;
End
可以使用microtime
功能這一點。從the documentation:
microtime
- 返回微秒電流Unix時間戳
如果
get_as_float
設置爲TRUE
,然後microtime()
返回float,它代表以秒爲單位的當前時間自Unix紀元精確到最近的微秒。
實例:
$start = microtime(true);
while (...) {
}
$time_elapsed_secs = microtime(true) - $start;
如果你想用返回值進行計算,你需要'microtime(true)'。 – lonesomeday 2011-06-05 21:29:37
我知道這是waaaaaay太晚了(差不多4年),但作爲一個評論...使用這些計算(使用參數'get_as_float'爲'true')會給你** **結果**,根據PHP文檔。 – 2015-03-31 02:34:09
@AlejandroIván:不,它不。 get_as_float將返回一個FLOAT而不是一個STRING,所以你可以用返回值進行計算......檢查http://php.net/manual/en/function.microtime.php:如果get_as_float設置爲TRUE,那麼microtime()返回一個浮點數,它表示自Unix時期以來的秒數,精確到最近的微秒。 – patrick 2015-07-06 15:13:52
參見microtime()。
$start = microtime(true);
for ($i = 0; $i < 10000; ++$i) {
// do something
}
$total = microtime(true) - $start;
echo $total;
你有正確的想法,但更精確的時序是可用的microtime()功能。
如果裏面是什麼循環快,有可能是明顯的運行時間將爲零。如果是這樣,圍繞代碼包裝另一個循環,並重復調用它。確保將差異除以迭代次數以獲得每次一次的時間。我有需要10,000,000次迭代的簡介代碼才能獲得一致,可靠的計時結果。
在腳本的beggining創建文件loadtime.php
<?php
class loadTime{
private $time_start = 0;
private $time_end = 0;
private $time = 0;
public function __construct(){
$this->time_start= microtime(true);
}
public function __destruct(){
$this->time_end = microtime(true);
$this->time = $this->time_end - $this->time_start;
echo "Loaded in $this->time seconds\n";
}
}
比,後<?php
寫include 'loadtime.php'; $loadtime=new loadTime();
當頁面是在年底將有寫「在x秒加載」
裝整潔!但是,如果你沒有明確地銷燬你的對象,輸出將出現在關閉'
可以擺弄)microtime中的大片(報表,如果您需要在此生產,但如果它只是用於測試,只需使用[Xdebug的的分析器(http://www.xdebug.org/docs/profiler)。沒有混亂的代碼是一個真正的優點。 – Wrikken 2011-06-05 21:39:39