PHP程式加速探索[5]–指令碼執行速度測試2

來源:互聯網
上載者:User

現在我們看看另一個測試指令碼已耗用時間的方法--使用Benchmark_Timer類來測試一段代碼執行所消耗的時間及這一段代碼中每次調用與下一次調用間的時間。

benchmark2.php


require_once 'Benchmark/Timer.php';
$timer = new Benchmark_Timer();

$timer->start();
$timer->setMarker('start_myFunction');

for($i=0; $i<10; $i++){
    myFunction($argument);
}
$timer->setMarker('end_myFunction');
$timer->stop();
$profiling = $timer->getProfiling();

echo '

Time elapsed: '

.
$timer->timeElapsed('start_myFunction','end_myFunction') .'

';
echo '

'

;
print_r($profiling);
echo '';
exit;

function myFunction($var) {
static $counter = 0;
// do something
echo $counter++ . ' ';
}
?>

首先,建立一個benchmark timer對象$timer。然後調用start()方法,表示開始計時。 SetMaker()方法用來標記要測試的程式碼片段。MyFunction()函數在迴圈中被調用,表示一段要執行的代碼(當然實際中不會這麼簡單)。然後再用$timer對象的setMarker()方法標記程式執行終點。分析資訊用getProfiling()來擷取。在兩個標記間程式執行消耗的時間用timeElapsed()方法計算出來(就像例子中的迴圈)。最後,用print_r()輸出資訊到螢幕:

0 1 2 3 4 5 6 7 8 9

Time elapsed: 0.000594

Array
(
    [0] => Array
        (
            [name] => Start
            [time] => 1085730111.27175200
            [diff] => -
            [total] => 1085730111.271752
        )
 
    [1] => Array
        (
            [name] => start_myFunction
            [time] => 1085730111.27203800
            [diff] => 0.000286
            [total] => 1085730111.272038
        )
 
    [2] => Array
        (
            [name] => end_myFunction
            [time] => 1085730111.27263200
            [diff] => 0.000594
            [total] => 1085730111.272632
        )
 
    [3] => Array
        (
            [name] => Stop
            [time] => 1085730111.27271800
            [diff] => 0.000086
            [total] => 1085730111.272718
       )
)

通過這種方法,你可以在代碼中設定大量時間區段標記,擷取每段代碼執行時消耗的時間,很容易可以看出到底是哪一部份的代碼影響了整個程式的運行效率。然後開始著手對這部份代碼進行改進。

用以上兩種方法,你可以找出代碼中最影響速度的部份代碼。另外還可以用來對最佳化後的代碼進行測試,看看到底執行速度提高了多少。通過測試->最佳化->測試->最佳化 …這樣不斷迴圈,你可以最終確定提供最佳效率的代碼。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.