跟踪 PHP 中的脚本执行时间
2022-08-30 05:59:18
PHP 必须跟踪特定脚本使用的 CPU 时间量,以便强制实施max_execution_time限制。
有没有办法在脚本中访问它?我想在我的测试中包括一些日志记录,关于实际PHP中消耗了多少CPU(当脚本坐着等待数据库时,时间不会增加)。
我正在使用Linux盒子。
PHP 必须跟踪特定脚本使用的 CPU 时间量,以便强制实施max_execution_time限制。
有没有办法在脚本中访问它?我想在我的测试中包括一些日志记录,关于实际PHP中消耗了多少CPU(当脚本坐着等待数据库时,时间不会增加)。
我正在使用Linux盒子。
如果您只需要挂钟时间,而不是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
在 unixoid 系统上(在 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实例,则无需计算差异。