2009-11-13 66 views
4

我有兩個功能,其執行時間我想比較:PHP基準功能計時器腳本

function subject_one() { 
    $str = preg_match_all(...[SNIP]...); 
    // ...[SNIP]... 
    return $str; 
} 

function subject_two() { 
    $reader = new XMLReader; 
    $writer = new XMLWriter; 
    // ...[SNIP]... 
    echo $str; 
} 

是否可以編寫一個函數來做到這一點?

例如:我已經看到代碼添加到劇本,我想避免,如果可能的話它的頂部和底部

function benchmark_two_functions($first_function, $second_function) { 
    // do stuff 
    return $length_of_time_to_complete_each_function 
} 

大多數示例。

回答

11

試試這個

function subject_one(){ 
    sleep(1); 
} 

function subject_two(){ 
    sleep(5); 
} 

/* Result should be ~4 */ 
print benchmark_two_functions('subject_one','subject_two'); 

function getmicrotime() { 
    list($usec, $sec) = explode(" ",microtime()); 
    return ((float)$usec + (float)$sec); 
} 

function benchmark_two_functions($first_function, $second_function){ 
    $start = getmicrotime(); 
    $first_function(); 
    $exec_time_first = getmicrotime() - $start; 

    $start = getmicrotime(); 
    $second_function(); 
    $exec_time_second = getmicrotime() - $start; 

    return $exec_time_first - $exec_time_second; 
} 
+0

我想知道如何在功能'benchmark_two_functions()'可以修改運行'subject_one()'和'subject_two()'多次? – Jeff 2009-11-14 16:15:28

0

PEAR has a Benchmark庫PHP分析。它工作得很好,但是如果你有對你的服務器的root權限並且可以安裝它,也許XDebug是一個更好的工具。