分析PHP脚本最简单的方法是什么?
我喜欢在上面添加一些东西,告诉我所有函数调用的转储以及它们花了多长时间,但我也可以在特定的函数周围放一些东西。
我尝试了微时间功能:
$then = microtime();
myFunc();
$now = microtime();
echo sprintf("Elapsed: %f", $now-$then);
但这有时会给我带来负面结果。另外,在我的代码中散布这些代码会带来很多麻烦。
分析PHP脚本最简单的方法是什么?
我喜欢在上面添加一些东西,告诉我所有函数调用的转储以及它们花了多长时间,但我也可以在特定的函数周围放一些东西。
我尝试了微时间功能:
$then = microtime();
myFunc();
$now = microtime();
echo sprintf("Elapsed: %f", $now-$then);
但这有时会给我带来负面结果。另外,在我的代码中散布这些代码会带来很多麻烦。
当前回答
XDebug并不稳定,而且并不总是适用于特定的php版本。例如,在一些服务器上,我仍然运行php-5.1.6,这是RedHat RHEL5附带的(顺便说一下,所有重要问题仍然会收到更新),而且最近的XDebug甚至不使用这个php编译。所以我最终切换到DBG调试器 它的php基准测试为函数、方法、模块甚至行提供了计时。
其他回答
PECL XHPROF看起来也很有趣。它有可点击的HTML界面,用于查看报告和相当简单的文档。不过我还没有测试过。
不需要扩展,只需使用这两个函数进行简单的概要分析。
// Call this at each point of interest, passing a descriptive string
function prof_flag($str)
{
global $prof_timing, $prof_names;
$prof_timing[] = microtime(true);
$prof_names[] = $str;
}
// Call this when you're done and want to see the results
function prof_print()
{
global $prof_timing, $prof_names;
$size = count($prof_timing);
for($i=0;$i<$size - 1; $i++)
{
echo "<b>{$prof_names[$i]}</b><br>";
echo sprintf(" %f<br>", $prof_timing[$i+1]-$prof_timing[$i]);
}
echo "<b>{$prof_names[$size-1]}</b><br>";
}
下面是一个例子,在每个检查点调用prof_flag(),并在结束时调用prof_print():
prof_flag("Start");
include '../lib/database.php';
include '../lib/helper_func.php';
prof_flag("Connect to DB");
connect_to_db();
prof_flag("Perform query");
// Get all the data
$select_query = "SELECT * FROM data_table";
$result = mysql_query($select_query);
prof_flag("Retrieve data");
$rows = array();
$found_data=false;
while($r = mysql_fetch_assoc($result))
{
$found_data=true;
$rows[] = $r;
}
prof_flag("Close DB");
mysql_close(); //close database connection
prof_flag("Done");
prof_print();
输出如下所示:
开始0.004303连接DB 0.003518执行查询0.000308检索数据0.000009关闭DB 0.000049Done
老实说,我认为使用NewRelic进行分析是最好的。
这是一个PHP扩展,似乎并不会减慢运行时,他们为你做监控,允许体面的钻。在昂贵的版本中,他们允许重钻(但我们负担不起他们的定价模式)。
尽管如此,即使使用免费/标准计划,大多数容易实现的目标也是显而易见和简单的。我也喜欢它可以给你一个关于DB交互的想法。
我喜欢使用phpDebug进行分析。 http://phpdebug.sourceforge.net/www/index.html
它输出使用的任何SQL以及所有包含的文件的所有时间/内存使用情况。显然,它在抽象的代码上工作得最好。
对于函数和类分析,我只使用microtime() + get_memory_usage() + get_peak_memory_usage()。
你们都应该检查一下这个新的php分析器。
https://github.com/NoiseByNorthwest/php-spx
它重新定义了php分析器收集和显示结果的方式。 PHP-SPX不只是输出特定函数调用的总数和执行它所花费的总时间,而是以一种完全可读的方式显示了请求执行的整个时间轴。下图是它提供的GUI界面。