我怎样才能测量加载页面所需的时间(包括各种不同的PHP语句)?
与此类似的统计数据可在这里找到 - http://talks.php.net/show/drupal08/24
有很多方法可以实现这个功能。我个人喜欢使用microtime,以下是具体方法:
// Start of code
$time = microtime(true); // Gets microseconds
// Rest of code
// End of code
echo "Time Elapsed: ".(microtime(true) - $time)."s";
这将为您提供微秒级的精确度。
如果您正在编写命令行脚本(例如 Facebook puzzles),则可以使用 time 命令。
time php dancebattle.php ~/input.dat
Win
real 0m0.152s
user 0m0.142s
sys 0m0.012s
我忘记了如何监测页面加载时间(从浏览器)。您可以使用Firebug的NET选项卡(适用于Firefox)来做到这一点。它将允许您观察各种文件的加载情况(AJAX、JS、CSS、图像等)。
ab
),它是由Apache提供的:
$ time curl http://www.example.com/
请尝试访问 https://github.com/fotuzlab/appgati
它允许在代码中定义步骤,并报告两个步骤之间的时间、内存使用情况、服务器负载等信息。
类似于:
$appgati->Step('1');
// Do some code ...
$appgati->Step('2');
$report = $appgati->Report('1', '2');
print_r($report);
示例输出数组:
Array
(
[Clock time in seconds] => 1.9502429962158
[Time taken in User Mode in seconds] => 0.632039
[Time taken in System Mode in seconds] => 0.024001
[Total time taken in Kernel in seconds] => 0.65604
[Memory limit in MB] => 128
[Memory usage in MB] => 18.237907409668
[Peak memory usage in MB] => 19.579357147217
[Average server load in last minute] => 0.47
[Maximum resident shared size in KB] => 44900
[Integral shared memory size] => 0
[Integral unshared data size] => 0
[Integral unshared stack size] =>
[Number of page reclaims] => 12102
[Number of page faults] => 6
[Number of block input operations] => 192
[Number of block output operations] =>
[Number of messages sent] => 0
[Number of messages received] => 0
[Number of signals received] => 0
[Number of voluntary context switches] => 606
[Number of involuntary context switches] => 99
)
生成页面所需的时间(由PHP代码中的内部计时器测量)
将其从服务器卸载的时间(由ab测量)
echo "<table border=1><tr><td>name</td><td>so far</td><td>delta</td><td>per cent</td></tr>";
reset($TIMER);
$start=$prev=current($TIMER);
$total=end($TIMER)-$start;
foreach($TIMER as $name => $value) {
$sofar=round($value-$start,3);
$delta=round($value-$prev,3);
$percent=round($delta/$total*100);
echo "<tr><td>$name</td><td>$sofar</td><td>$delta</td><td>$percent</td></tr>";
$prev=$value;
}
echo "</table>";
分析
,在优化过程中占据了最重要的位置。<?php
$statrttime = microtime();
$time = explode(' ', $statrttime);
$time = $time[1] + $time[0];
$start = $time;
?>
以下代码必须放在您的页面末尾。
<?php
$endtime = microtime();
$time = explode(' ', $endtime);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $start), 4);
echo 'Page load in '.$total_time.' seconds.';
?>
<?php
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$start = $time;
?>
<?php
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $start), 4);
echo 'Page generated in '.$total_time.' seconds.';
如果不起作用,请使用microtime(true)而不是microtime()
那个演示中的输出看起来好像是从 Siege (http://www.joedog.org/index/siege-home) 复制过来的。
另一个非常有用的工具,用于测试整个应用程序堆栈的“真实世界”性能是 Firebug (http://getfirebug.com/) 和 YSlow (http://developer.yahoo.com/yslow/)