分析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基准测试为函数、方法、模块甚至行提供了计时。
其他回答
如果减去microtimes会得到负的结果,请尝试使用参数为true的函数(microtime(true))。设置为true时,函数返回一个浮点数而不是字符串(如果调用时不带参数,则会这样做)。
不需要扩展,只需使用这两个函数进行简单的概要分析。
// 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
对于基准测试,就像在您的示例中一样,我使用pear Benchmark包。你设置标记来测量。该类还提供了一些表示帮助程序,或者您可以根据自己的需要处理数据。
我实际上用__destruct方法将它包装在另一个类中。当脚本退出时,输出将通过log4php记录到syslog,因此我有很多性能数据可以使用。
老实说,我认为使用NewRelic进行分析是最好的。
这是一个PHP扩展,似乎并不会减慢运行时,他们为你做监控,允许体面的钻。在昂贵的版本中,他们允许重钻(但我们负担不起他们的定价模式)。
尽管如此,即使使用免费/标准计划,大多数容易实现的目标也是显而易见和简单的。我也喜欢它可以给你一个关于DB交互的想法。
XDebug并不稳定,而且并不总是适用于特定的php版本。例如,在一些服务器上,我仍然运行php-5.1.6,这是RedHat RHEL5附带的(顺便说一下,所有重要问题仍然会收到更新),而且最近的XDebug甚至不使用这个php编译。所以我最终切换到DBG调试器 它的php基准测试为函数、方法、模块甚至行提供了计时。