文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>PHP程序加速探索[5]--脚本执行速度测试2

PHP程序加速探索[5]--脚本执行速度测试2

时间:2008-05-27  来源:剑心通明


现在我们看看另一个测试脚本运行时间的方法--使用Benchmark_Timer类来测试一段代码执行所消耗的时间及这一段代码中每次调用与下一次调用间的时间。
benchmark2.php
require_once 'Benchmark/Timer.php';
$timer = new Benchmark_Timer();
$timer->start();
$timer->setMarker('start_myFunction');
for($i=0; $i10; $i++){
    myFunction($argument);
}
$timer->setMarker('end_myFunction');
$timer->stop();
$profiling = $timer->getProfiling();
echo '
Time elapsed: '
.
$timer->timeElapsed('start_myFunction','end_myFunction') .'
';
echo ' ';
print_r($profiling);
echo '';
exit;
function myFunction($var) {
static $counter = 0;
// do something
echo $counter++ . ' ';
}
?>
首先,建立一个benchmark timer对象$timer。然后调用start()方法,表示开始计时。 SetMaker()方法用来标记要测试的代码段。MyFunction()函数在循环中被调用,表示一段要执行的代码(当然实际中不会这么简单)。然后再用$timer对象的setMarker()方法标记程序执行终点。分析信息用getProfiling()来获取。在两个标记间程序执行消耗的时间用timeElapsed()方法计算出来(就像例子中的循环)。最后,用print_r()输出信息到屏幕:
0 1 2 3 4 5 6 7 8 9
Time elapsed: 0.000594
Array(    [0] => Array        (            [name] => Start
            [time] => 1085730111.27175200
            [diff] => -
            [total] => 1085730111.271752        )     [1] => Array        (            [name] => start_myFunction
            [time] => 1085730111.27203800
            [diff] => 0.000286
            [total] => 1085730111.272038
        )     [2] => Array        (            [name] => end_myFunction
            [time] => 1085730111.27263200
            [diff] => 0.000594
            [total] => 1085730111.272632
        )     [3] => Array        (            [name] => Stop
            [time] => 1085730111.27271800
            [diff] => 0.000086
            [total] => 1085730111.272718
        ))
通过这种方法,你可以在代码中设置大量时间段标记,获取每段代码执行时消耗的时间,很容易可以看出到底是哪一部份的代码影响了整个程序的运行效率。然后开始着手对这部份代码进行改进。
用以上两种方法,你可以找出代码中最影响速度的部份代码。另外还可以用来对优化后的代码进行测试,看看到底执行速度提高了多少。通过测试->优化->测试->优化 …这样不断循环,你可以最终确定提供最佳效率的代码。


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载