为了强制执行max_execution_time限制,PHP必须跟踪特定脚本所使用的CPU时间。
是否有一种方法可以在脚本中访问它?我希望在测试中包含一些关于实际PHP中消耗了多少CPU的日志记录(当脚本等待数据库时,时间不会增加)。
我用的是Linux机顶盒。
为了强制执行max_execution_time限制,PHP必须跟踪特定脚本所使用的CPU时间。
是否有一种方法可以在脚本中访问它?我希望在测试中包含一些关于实际PHP中消耗了多少CPU的日志记录(当脚本等待数据库时,时间不会增加)。
我用的是Linux机顶盒。
当前回答
<?php
// Randomize sleeping time
usleep(mt_rand(100, 10000));
// As of PHP 5.4.0, REQUEST_TIME_FLOAT is available in the $_SERVER superglobal array.
// It contains the timestamp of the start of the request with microsecond precision.
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
echo "Did nothing in $time seconds\n";
?>
其他回答
我认为您应该看看xdebug。分析选项将为您了解许多与流程相关的项目提供一个良好的开端。
http://www.xdebug.org/
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时间”
作为一种替代方法,你可以把这一行放在你的代码块中,并检查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/
<?php
// Randomize sleeping time
usleep(mt_rand(100, 10000));
// As of PHP 5.4.0, REQUEST_TIME_FLOAT is available in the $_SERVER superglobal array.
// It contains the timestamp of the start of the request with microsecond precision.
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
echo "Did nothing in $time seconds\n";
?>
在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实例,则不需要计算差异。