分析PHP脚本最简单的方法是什么?
我喜欢在上面添加一些东西,告诉我所有函数调用的转储以及它们花了多长时间,但我也可以在特定的函数周围放一些东西。
我尝试了微时间功能:
$then = microtime();
myFunc();
$now = microtime();
echo sprintf("Elapsed: %f", $now-$then);
但这有时会给我带来负面结果。另外,在我的代码中散布这些代码会带来很多麻烦。
分析PHP脚本最简单的方法是什么?
我喜欢在上面添加一些东西,告诉我所有函数调用的转储以及它们花了多长时间,但我也可以在特定的函数周围放一些东西。
我尝试了微时间功能:
$then = microtime();
myFunc();
$now = microtime();
echo sprintf("Elapsed: %f", $now-$then);
但这有时会给我带来负面结果。另外,在我的代码中散布这些代码会带来很多麻烦。
当前回答
你们都应该检查一下这个新的php分析器。
https://github.com/NoiseByNorthwest/php-spx
它重新定义了php分析器收集和显示结果的方式。 PHP-SPX不只是输出特定函数调用的总数和执行它所花费的总时间,而是以一种完全可读的方式显示了请求执行的整个时间轴。下图是它提供的GUI界面。
其他回答
我喜欢使用phpDebug进行分析。 http://phpdebug.sourceforge.net/www/index.html
它输出使用的任何SQL以及所有包含的文件的所有时间/内存使用情况。显然,它在抽象的代码上工作得最好。
对于函数和类分析,我只使用microtime() + get_memory_usage() + get_peak_memory_usage()。
对于基准测试,就像在您的示例中一样,我使用pear Benchmark包。你设置标记来测量。该类还提供了一些表示帮助程序,或者您可以根据自己的需要处理数据。
我实际上用__destruct方法将它包装在另一个类中。当脚本退出时,输出将通过log4php记录到syslog,因此我有很多性能数据可以使用。
我会大胆地尝试一下BlackFire。
这是我用puphpet把这个virtualBox放在一起,用来测试不同的php框架,如果需要,请随意分叉和/或分发:)
https://github.com/webit4me/PHPFrameworks
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