为了强制执行max_execution_time限制,PHP必须跟踪特定脚本所使用的CPU时间。

是否有一种方法可以在脚本中访问它?我希望在测试中包含一些关于实际PHP中消耗了多少CPU的日志记录(当脚本等待数据库时,时间不会增加)。

我用的是Linux机顶盒。


当前回答

您可能只想知道部分脚本的执行时间。为部分或整个脚本计时的最灵活的方法是创建3个简单的函数(这里给出了过程代码,但您可以通过在它周围放置类timer{}并进行一些调整将其转换为类)。这段代码工作,只需复制粘贴并运行:

$tstart = 0;
$tend = 0;

function timer_starts()
{
global $tstart;

$tstart=microtime(true); ;

}

function timer_ends()
{
global $tend;

$tend=microtime(true); ;

}

function timer_calc()
{
global $tstart,$tend;

return (round($tend - $tstart,2));
}

timer_starts();
file_get_contents('http://google.com');
timer_ends();
print('It took '.timer_calc().' seconds to retrieve the google page');

其他回答

最便宜也是最麻烦的方法是在代码中想要进行基准测试的地方进行microtime()调用。在数据库查询之前和之后执行它,从脚本执行时间的其余部分中删除这些持续时间就很简单了。

提示:PHP执行时间很少会导致脚本超时。如果一个脚本超时,它几乎总是调用外部资源。

PHP微时间文档: http://us.php.net/microtime

我认为您应该看看xdebug。分析选项将为您了解许多与流程相关的项目提供一个良好的开端。

http://www.xdebug.org/

$_SERVER[REQUEST_TIME“]

看看这个。即。

...
// your codes running
...
echo (time() - $_SERVER['REQUEST_TIME']);

作为一种替代方法,你可以把这一行放在你的代码块中,并检查php日志,对于非常慢的函数,它非常有用:

trigger_error("Task done at ". strftime('%H:%m:%S', time()), E_USER_NOTICE); 

严肃的调试使用XDebug + Cachegrind,请参见https://blog.nexcess.net/2011/01/29/diagnosing-slow-php-execution-with-xdebug-and-kcachegrind/

talal7860回答的简短版本

<?php
// At start of script
$time_start = microtime(true); 

// Anywhere else in the script
echo 'Total execution time in seconds: ' . (microtime(true) - $time_start);

正如所指出的,这是“wallclock时间”而不是“cpu时间”