为了强制执行max_execution_time限制,PHP必须跟踪特定脚本所使用的CPU时间。
是否有一种方法可以在脚本中访问它?我希望在测试中包含一些关于实际PHP中消耗了多少CPU的日志记录(当脚本等待数据库时,时间不会增加)。
我用的是Linux机顶盒。
为了强制执行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');
其他回答
我认为您应该看看xdebug。分析选项将为您了解许多与流程相关的项目提供一个良好的开端。
http://www.xdebug.org/
在unix系统上(在Windows上的php 7+中也是如此),你可以使用getrusage,像这样:
// Script start
$rustart = getrusage();
// Code ...
// Script end
function rutime($ru, $rus, $index) {
return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
- ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
}
$ru = getrusage();
echo "This process used " . rutime($ru, $rustart, "utime") .
" ms for its computations\n";
echo "It spent " . rutime($ru, $rustart, "stime") .
" ms in system calls\n";
注意,如果要为每个测试生成一个php实例,则不需要计算差异。
如果你需要的是挂钟时间,而不是CPU执行时间,那么计算起来很简单:
//place this before any script you want to calculate time
$time_start = microtime(true);
//sample script
for($i=0; $i<1000; $i++){
//do anything
}
$time_end = microtime(true);
//dividing with 60 will give the execution time in minutes otherwise seconds
$execution_time = ($time_end - $time_start)/60;
//execution time of the script
echo '<b>Total Execution Time:</b> '.$execution_time.' Mins';
// if you get weird results, use number_format((float) $execution_time, 10)
注意,这将包括PHP等待外部资源(如磁盘或数据库)的时间,而max_execution_time没有使用这个时间。
当PHP中有闭包功能时,为什么我们不从中获益呢?
function startTime(){
$startTime = microtime(true);
return function () use ($startTime){
return microtime(true) - $startTime;
};
}
现在,在上述函数的帮助下,我们可以像这样跟踪时间
$stopTime = startTime();
//some code block or line
$elapsedTime = $stopTime();
每次调用startTime函数都会启动一个单独的时间跟踪器。所以你可以想启动多少就启动多少,也可以在任何你想要的地方停止它们。
您可能只想知道部分脚本的执行时间。为部分或整个脚本计时的最灵活的方法是创建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');