您好,欢迎访问一九零五行业门户网

提高php程序性能和负载测试

一篇关于提高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版本.
另外提速技巧是在能不使用正则的时候尽量不要用,通常可替代的方案会比使用正则效率更高.
文章链接:
随便收藏,请保留本文地址!
其它类似信息

推荐信息