cpu_get_usage in php?

﹥>﹥吖頭↗ 提交于 2019-12-05 06:12:14

Hate to answer my own question but I did a lot of research, and here I go... Basically what I did was this...

        $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;
                                              }

As you can see I used a getrusage php built-in function. Which gives out an array with a whole bunch of info, of which most was pretty useless to me, except ru_utime.tv_usec(user time) and ru_stime.tv_usec(system time). To see how much CPU power the script has consumed, we need to look at the 'user time' and 'system time' values and as you can see in the code, add it to get the time which is in fact a cpu usage.

function cpu_usage(){
    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;
}

Usage:

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";

In simple cases it gives the same, as microtime, but with less precision. The same function for microtime:

function stopwatch(){
    static $time=0;
    $prev=$time;
    $time=microtime(true);
    return $time-$prev;
}

Of coarse, not to use like this:

stopwatch();
f(); // some function, which calls `stopwatch` in itself too
echo stopwatch();

And how about..?

$pid = getmypid();
$cpu = exec("ps hup $pid|awk '{print $3}'");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!