PHP Cookbook读书笔记 – 第21章性能提升和负载测试

概述

虽然PHP本身的速度已经相当快了,也还是有一些工具和技巧用来提升其运行的速度。对在开发过程中进行优化的时间点一直是备受争议的话题,优化过早,可能为不必要的细节浪费时间;优化太晚,可能会发现自己不得不重写大段的代码。

优化不仅是提高其执行速度,几乎只有在少数的情况下需要更快的执行速度,而更常见的情况是节省编程和故障排除的时间。这些问题都是需要在优化的时候考虑的。

本章介绍了一些方法用来计算程序的执行时间,介绍了程序优化办法,也简单的介绍了如何对网站进行压力测试。

计算执行的时间

通过下面这个简单的方法可以计算一段程序的执行时间(微妙)

$start_time = microtime(true);

//一些需要计算时间的代码
//... code here ...

print('代码的运行时间是:'.getExecTime($start_time));

function getExecTime($start_time)
{
	return microtime(true)-$start_time;
}

PEAR的Benchmark模块提供了更详细的时间统计功能

require_once 'Benchmark/Timer.php';
$timer =& new Benchmark_Timer(true);
$timer->start();
// 设置函数
$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结构和ticks指令可以实现自动记录每一行PHP代码执行的时间

// 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");

// 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),通过设置可以生成跟踪文件,对文件进行分析可以得到脚本的详细信息

网站压力测试

人们常混淆压力测试和基准测试。基准测试是一种由单独的开发者完成的临时活动,常用Apache HTTP测试工具——ab,该工具可以测试一台HTTP服务器每秒能相应的请求数。压力测试是一种能中断你WEB应用程序的测试技术,通过对断点测试,能识别并修复应用程序中的弱点,为何时购置新硬件提供依据。常用的开源工具是Siege。

提速技巧

通过安装PHP加速器可以有效的提供PHP的执行速度,常见的三种加速器是Alternative PHP Cache(APC)、eAccelerator和ionCube PHP Accelerator(PHPA)。另外需要注意的是加速器的兼容性通常会滞后于新发布的PHP版本。

另外提速技巧是在能不使用正则的时候尽量不要用,通常可替代的方案会比使用正则效率更高。

原文地址:https://www.cnblogs.com/Excellent/p/2255297.html