问题描述
|
我有一些php代码,
代码中的某些内容(大部分代码)导致页面加载最多需要30秒,
有没有一种简单的方法来找出代码的哪一部分正在执行此操作?
解决方法
尝试对xdebug使用概要分析/跟踪:
使用xdebug对PHP应用程序进行性能分析并使用xdebug跟踪PHP应用程序
,如果您使用的是Zend Studio,则可以使用其分析器。或使用xdebug配置文件。
否则,您可以在函数调用周围放置计时器,以缩小搜索范围。
就像是
$startTime = microtime();
... code to execute ...
$timeSpent = microtime() - $startTime;
您也可以使用PECL APD扩展名
<?php
apd_set_pprof_trace();
... rest of your code ...
这将为您提供类似于以下内容的输出
Trace for /yourscript.php
Total Elapsed Time = 0.00
Total System Time = 0.00
Total User Time = 0.00
Real User System secs/ cumm
%Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name
--------------------------------------------------------------------------------------
100.0 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0000 0.0009 0 main
56.9 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0005 0.0005 0 apd_set_pprof_trace
28.0 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 foo
14.3 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 bar
祝好运!
,您可以按照以下步骤通过PHP中的代码块简单地检查代码的执行时间:
start_time = get_time_now
<execution block 1>
execution_time = get_time_now - start_time
start_time = get_time_now
<execution block 2>
execution_time = get_time_now - start_time
因此,每次执行您的特定代码块时,都将在第二秒内检查并打印出该代码块。您需要做的是将计算添加到代码的每个块中,以测试哪个正在减慢页面速度。我已经编写了示例代码供您参考:
<?php
$time_start = microtime(true);
// Execution 1
usleep(300); // say it sleeps for a while,like executing something
$time = microtime(true) - $time_start;
echo \"Execution 1 is done in $time seconds \\n\";
$time_start = microtime(true);
// Execution 2
usleep(300); // say it sleeps for a while,like executing something
$time = microtime(true) - $time_start;
echo \"Execution 2 is done in $time seconds \\n\";
$time_start = microtime(true);
// Execution 3
usleep(3000000); // this gonna slow down your page
$time = microtime(true) - $time_start;
echo \"Execution 3 is done in $time seconds\";
echo \"And it\'s slowing down your page \\n\";
?>
但是请注意,很难说出简单指令之间的区别,因为它们之间的差别仅不到毫秒。但是,如果有一条复杂的指令使您的页面速度变慢,则很容易注意到它,因为它会与众不同:)