PHP程式加速探索之指令碼執行速度測試

來源:互聯網
上載者:User
程式|指令碼|速度|執行     前面有提到,只有找到影響速度的代碼,我們才有可能進行最佳化。PEAR的benchmark包中的Benchmark_Timer類和Benchmark_Iterate類,可以用來很方便地測試指令碼執行的速度。(關於PEAR的安裝與配置請自行查看相關資料) 。

  首先用Benchmark_Iterate類來測試程式中某個函數或類的某個方法的執行時間。

  benchmark1.php

require_once('Benchmark/Iterate.php');
$benchmark = new Benchmark_Iterate();

$benchmark->run(10, 'myFunction','test');
$result = $benchmark->get();
echo "

"; print_r($result); echo "
";
exit;

function myFunction($var) {
// do something
echo 'Hello ';
}

?>


  建立benchmark Iterate對象$benchmark,這個對象用來執行myFunction函數10次。

  $argument變數每次都傳遞給myFunction. 多次啟動並執行分析結果存入$result,然後用benchmark對象的get()方法來擷取。這個結果用print_r()輸出到螢幕。通常會輸出這樣的結果:

Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello

Array
(
[1] => 0.000427 [2] => 0.000079 [3] => 0.000072 [4] => 0.000071 [5] => 0.000076 [6] => 0.000070 [7] => 0.000073 [8] => 0.000070 [9] => 0.000074 [10] => 0.000072 [mean] => 0.000108 [iterations] => 10)


  myFunction的每次執行,benchmark對象都會跟蹤執行時間。並且會計算平均的執行時間([mean]那一行)。通過多次運行目標函數,你可以得到該函數的平均已耗用時間。

  在實際測試中,函數的次數應當至少1000次左右,這樣可以得到較客觀的結果。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.