cpu_get_usage in php?

我怕爱的太早我们不能终老 提交于 2019-12-07 02:35:43

问题


I have created a benchmark class that allows the user to insert for example

$timer->checkpoint('1');

to check out some code for time,memory consumption and such.... and at the end of the code if she/he wants to test it she/he has to insert

$result=$timer->result();

this gives out some data to public function result() like e.g. memory usage (using memory_get_peak_usage) and time consumption (microtime()).

This all works just fine for me.

But how can I use the combination of existing built-in php functions to get a value that can be considered a CPU consumption?

It has been quite easy to calculate how much time has been spent on a certain piece of code using the built-in functions, but I've been having trouble thinking of a way how to get the CPU consumption for a certain piece of code.


回答1:


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.




回答2:


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();



回答3:


And how about..?

$pid = getmypid();
$cpu = exec("ps hup $pid|awk '{print $3}'");


来源:https://stackoverflow.com/questions/8413323/cpu-get-usage-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!