为了强制执行max_execution_time限制,PHP必须跟踪特定脚本所使用的CPU时间。
是否有一种方法可以在脚本中访问它?我希望在测试中包含一些关于实际PHP中消耗了多少CPU的日志记录(当脚本等待数据库时,时间不会增加)。
我用的是Linux机顶盒。
为了强制执行max_execution_time限制,PHP必须跟踪特定脚本所使用的CPU时间。
是否有一种方法可以在脚本中访问它?我希望在测试中包含一些关于实际PHP中消耗了多少CPU的日志记录(当脚本等待数据库时,时间不会增加)。
我用的是Linux机顶盒。
当前回答
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时间”
其他回答
$_SERVER[REQUEST_TIME“]
看看这个。即。
...
// your codes running
...
echo (time() - $_SERVER['REQUEST_TIME']);
最便宜也是最麻烦的方法是在代码中想要进行基准测试的地方进行microtime()调用。在数据库查询之前和之后执行它,从脚本执行时间的其余部分中删除这些持续时间就很简单了。
提示:PHP执行时间很少会导致脚本超时。如果一个脚本超时,它几乎总是调用外部资源。
PHP微时间文档: http://us.php.net/microtime
在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实例,则不需要计算差异。
您可能只想知道部分脚本的执行时间。为部分或整个脚本计时的最灵活的方法是创建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');
在页面底部居中打印的小脚本,在服务器调用时以微秒精度开始脚本执行。
为了不扭曲结果,并与页面中的内容100%兼容,我使用浏览器端本地javascript代码段在页面上编写结果。
//Uncomment the line below to test with 2 seconds
//usleep(2000000);
$prec = 5; // numbers after comma
$time = number_format(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], $prec, '.', '');
echo "<script>
if(!tI) {
var tI=document.createElement('div');
tI.style.fontSize='8px';
tI.style.marginBottom='5px';
tI.style.position='absolute';
tI.style.bottom='0px';
tI.style.textAlign='center';
tI.style.width='98%';
document.body.appendChild(tI);
}
tI.innerHTML='$time';
</script>";
另一种方法是使代码片段尽可能小,并使用样式表中的类对其进行样式化。
替换回显…;与以下部分分开: echo "<script>if(!tI){var tI=document.createElement('div');tI. classname ='ldtme';document.body.appendChild(tI);}tI. innerhtml ='$time'; 在CSS中创建并填充.ldtme{…}类。