为了强制执行max_execution_time限制,PHP必须跟踪特定脚本所使用的CPU时间。
是否有一种方法可以在脚本中访问它?我希望在测试中包含一些关于实际PHP中消耗了多少CPU的日志记录(当脚本等待数据库时,时间不会增加)。
我用的是Linux机顶盒。
为了强制执行max_execution_time限制,PHP必须跟踪特定脚本所使用的CPU时间。
是否有一种方法可以在脚本中访问它?我希望在测试中包含一些关于实际PHP中消耗了多少CPU的日志记录(当脚本等待数据库时,时间不会增加)。
我用的是Linux机顶盒。
当前回答
$_SERVER[REQUEST_TIME“]
看看这个。即。
...
// your codes running
...
echo (time() - $_SERVER['REQUEST_TIME']);
其他回答
如果你像这样格式化秒的输出,它会更漂亮:
echo "Process took ". number_format(microtime(true) - $start, 2). " seconds.";
将打印
Process took 6.45 seconds.
这比
Process took 6.4518549156189 seconds.
进一步扩展Hamid的回答,我写了一个可以重复启动和停止的helper类(用于在循环中进行分析)。
class ExecutionTime
{
private $startTime;
private $endTime;
private $compTime = 0;
private $sysTime = 0;
public function Start(){
$this->startTime = getrusage();
}
public function End(){
$this->endTime = getrusage();
$this->compTime += $this->runTime($this->endTime, $this->startTime, "utime");
$this->systemTime += $this->runTime($this->endTime, $this->startTime, "stime");
}
private function runTime($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));
}
public function __toString(){
return "This process used " . $this->compTime . " ms for its computations\n" .
"It spent " . $this->systemTime . " ms in system calls\n";
}
}
我认为您应该看看xdebug。分析选项将为您了解许多与流程相关的项目提供一个良好的开端。
http://www.xdebug.org/
要显示分钟和秒,您可以使用:
$startTime = microtime(true);
$endTime = microtime(true);
$diff = round($endTime - $startTime);
$minutes = floor($diff / 60); //only minutes
$seconds = $diff % 60;//remaining seconds, using modulo operator
echo "script execution time: minutes:$minutes, seconds:$seconds"; //value in seconds
当PHP中有闭包功能时,为什么我们不从中获益呢?
function startTime(){
$startTime = microtime(true);
return function () use ($startTime){
return microtime(true) - $startTime;
};
}
现在,在上述函数的帮助下,我们可以像这样跟踪时间
$stopTime = startTime();
//some code block or line
$elapsedTime = $stopTime();
每次调用startTime函数都会启动一个单独的时间跟踪器。所以你可以想启动多少就启动多少,也可以在任何你想要的地方停止它们。