我创建了一个基准类,允许用户插入例如
$timer->checkpoint('1');
检查一些代码的时间、内存消耗等......并且在代码末尾,如果她/他想测试它,她/他必须插入
$result=$timer->result();
这会向公共函数 result() 提供一些数据,例如内存使用量(使用 memory_get_peak_usage)和时间消耗(microtime())。
这一切对我来说都很好。
但是如何利用现有的内置php函数的组合来得到一个可以被认为是CPU消耗的值?
使用内置函数计算某段代码花费了多少时间非常容易,但我一直在思考如何获取某段代码的CPU消耗的方法.
不想回答我自己的问题,但我做了很多研究,现在我开始...... 基本上我所做的就是这个...
$dat=getrusage();
foreach ($dat as $key => $val) {
$usertime= $dat['ru_utime.tv_usec'];
$systemtime= $dat['ru_stime.tv_usec'];
$finalresultcpu= ($systemtime + $usertime);
}
$this->_cpuTrackers[$name]=$finalresultcpu;
return $this;
}
如你所见,我使用了 getrusage php 内置函数。它给出了一个包含大量信息的数组,其中大多数对我来说毫无用处,除了 ru_utime.tv_usec(用户时间)和 ru_stime.tv_usec(系统时间)。要查看脚本消耗了多少 CPU 功率,我们需要查看“用户时间”和“系统时间”值,正如您在代码中看到的那样,将其相加即可获取实际上是 CPU 使用情况的时间。
function cpu_time(){
static $R=0;
$r=$R;
$R=getrusage();
$R= $R['ru_utime.tv_sec']*1000000+$R['ru_utime.tv_usec']+
$R['ru_stime.tv_sec']*1000000+$R['ru_stime.tv_usec'];
return $R-$r;
}
用途:
cpu_time(); // optionally initiating, to measure time from this point,
// not from the script's beginning
// doing some stuff here
echo cpu_time()." elapsed\n";
// doing yet some stuff here
echo cpu_time()." elapsed\n";
在简单情况下,它给出的结果与
microtime
相同,但精度较低。
microtime
具有相同的功能:
function stopwatch(){
static $time=0;
$prev=$time;
$time=microtime(true);
return $time-$prev;
}
粗略地说,不要这样使用:
stopwatch();
f(); // some function, which calls `stopwatch` in itself too
echo stopwatch();
那……怎么样?
$pid = getmypid();
$cpu = exec("ps hup $pid|awk '{print $3}'");