一篇關(guān)于提高php程序性能和負載測試的實例代碼,有需要的朋友可以看看如何提高自己程序的性能.
計算執(zhí)行的時間,通過下面這個簡單的方法可以計算一段程序的執(zhí)行時間(微妙),代碼如下:
- $start_time = microtime(true);
- //一些需要計算時間的代碼
- //... code here ...
- print('代碼的運行時間是:'.getExecTime($start_time));
- function getExecTime($start_time)
- {
- return microtime(true)-$start_time;
- }PEAR的Benchmark模塊提供了更詳細的時間統(tǒng)計功能
- require_once 'Benchmark/Timer.php';
- $timer =& new Benchmark_Timer(true);
- $timer->start();
- // 設(shè)置函數(shù)
- $timer->setMarker('setup');
- // some more code executed here
- $timer->setMarker('middle');
- // even yet still more code here
- $timer->setmarker('done');
- // and a last bit of code here
- $timer->stop();
- $timer->display();通過declare結(jié)構(gòu)和ticks指令可以實現(xiàn)自動記錄每一行PHP代碼執(zhí)行的時間
- // A function that records the time when it is called
- function profile($dump = FALSE)
- {
- static $profile;
- // Return the times stored in profile, then erase it
- if ($dump) {
- $temp = $profile;
- unset($profile);
- return ($temp);
- }
- $profile[] = microtime();
- }
- // Set up a tick handler
- register_tick_function("profile");
- //開源代碼Vevb.com
- // Initialize the function before the declare block
- profile();
- // Run a block of code, throw a tick every 2nd statement
- declare(ticks=2) {
- for ($x = 1; $x < 50; ++$x) {
- echo similar_text(md5($x), md5($x*$x)), ";";
- }
- }
- // Display the data stored in the profiler
print_r(profile (TRUE));注意:ticks 指令在 PHP 5.3.0 中是過時指令,將會從 PHP 6.0.0 移除.
代碼排錯
主要介紹的是Advanced PHP Debugger(APD),通過設(shè)置可以生成跟蹤文件,對文件進行分析可以得到腳本的詳細信息.
網(wǎng)站壓力測試
人們常混淆壓力測試和基準(zhǔn)測試,基準(zhǔn)測試是一種由單獨的開發(fā)者完成的臨時活動,常用Apache HTTP測試工具——ab,該工具可以測試一臺HTTP服務(wù)器每秒能相應(yīng)的請求數(shù),壓力測試是一種能中斷你WEB應(yīng)用程序的測試技術(shù),通過對斷點測試,能識別并修復(fù)應(yīng)用程序中的弱點,為何時購置新硬件提供依據(jù),常用的開源工具是Siege.
提速技巧
通過安裝PHP加速器可以有效的提供PHP的執(zhí)行速度,常見的三種加速器是Alternative PHP Cache(APC)、eAccelerator和ionCube PHP Accelerator(PHPA),另外需要注意的是加速器的兼容性通常會滯后于新發(fā)布的PHP版本.
另外提速技巧是在能不使用正則的時候盡量不要用,通常可替代的方案會比使用正則效率更高.
新聞熱點
疑難解答