前面有提到,只有找到影响速度的代码,我们才有可能进行优化。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次左右,这样可以得到较客观的结果。
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器