13

I want to show percent CPU usage in PHP. Is not important if get values by cron in shell > output to file > parse in PHP or directly get value in php. I try many solutions found on internet but nothing was useful. With load average I can't display 0-100% graphic bar and functions I found for percentage output give me bad values or only value for first core. It would be nice to get number of percentage usage for every core. Is there solution for this?

EDIT:

I make temporary solution, it works good but it is not best way.

cron job every one minute run php script which exec command for grep cpu info from "top" and save it to file, on end script wait 3 seconds and loop 20-times (way to get update every 3 seconds) php script:

<?php
for($i=0; $i<=20; $i++) {
    //cpu load
    exec("top -b -n 1 | grep 'Cpu(s):' > /some/file.cpu");
    //ram usage
    exec("top -b -n 1 | grep 'Mem:' > /some/file.ram");
    //wait 3sec
    sleep(3);
}
?>

and now from this files I can parse informations.

New question is how to make daemon script to run this commands every 3 seconds. I think solution with php script and cron is only temporary solution and is not best way. daemon will be much better.

stix
  • 812
  • 2
  • 7
  • 22
  • Possible duplicate? http://stackoverflow.com/questions/4705759/how-to-get-cpu-usage-and-ram-usage-without-exec – Jon Oct 29 '12 at 23:54
  • 1
    not duplicate, i can use exec and phpsysinfo not solve my problem – stix Oct 30 '12 at 00:45

6 Answers6

18

after searching on forums and trying many methods, best accurate is this:

$stat1 = file('/proc/stat'); 
sleep(1); 
$stat2 = file('/proc/stat'); 
$info1 = explode(" ", preg_replace("!cpu +!", "", $stat1[0])); 
$info2 = explode(" ", preg_replace("!cpu +!", "", $stat2[0])); 
$dif = array(); 
$dif['user'] = $info2[0] - $info1[0]; 
$dif['nice'] = $info2[1] - $info1[1]; 
$dif['sys'] = $info2[2] - $info1[2]; 
$dif['idle'] = $info2[3] - $info1[3]; 
$total = array_sum($dif); 
$cpu = array(); 
foreach($dif as $x=>$y) $cpu[$x] = round($y / $total * 100, 1);

now stats are in $cpu['user'], $cpu['nice'], $cpu['sys'], $cpu['idle']

stix
  • 812
  • 2
  • 7
  • 22
6

The answer by Diyism as well as the suggestion on http://php.net/manual/en/function.sys-getloadavg.php didn't seem to work on CentOS 6.5 VPS. We had to change physical id to processor. Then it returns one core as ID 0 so the calculation needs +1 cores. Also, you need to multiply by 100 to get a percentile. Finally, that needs to be rounded for a nice looking percent. So here is an alternate thought that may work if you run into any of that:

<?php
$loads = sys_getloadavg();
$core_nums = trim(shell_exec("grep -P '^processor' /proc/cpuinfo|wc -l"));
$load = round($loads[0]/($core_nums + 1)*100, 2);
echo $load;
?>

So if load avg [0] was 0.50 on 2 core machine this would display a CPU load of 25%

dhaupin
  • 1,613
  • 2
  • 21
  • 24
4

I'm not 100% sure on what you're asking, but if I'm right, this answer might help you:

<?php
    exec('ps -aux', $processes);
    foreach($processes as $process)
    {
        $cols = split(' ', ereg_replace(' +', ' ', $process));
        if (strpos($cols[2], '.') > -1)
        {
            $cpuUsage += floatval($cols[2]);
        }
    }
    print($cpuUsage);
?>

The code provided was an answer from Devils Child for a similar question: https://stackoverflow.com/a/9846219/904242

Community
  • 1
  • 1
qrokodial
  • 45
  • 7
2

Use this:

<?php
$loads=sys_getloadavg();
$core_nums=trim(shell_exec("grep -P '^physical id' /proc/cpuinfo|wc -l"));
$load=$loads[0]/$core_nums;
echo $load;
?>
diyism
  • 12,477
  • 5
  • 46
  • 46
  • I would just avoid executing so many commands: `preg_match_all('/^processor/m', file_get_contents('/proc/cpuinfo'), $matches); $core_nums = count($matches[0]);` – brablc Dec 03 '15 at 07:58
1

you can use "top -n 1" for getting cpu percentage. this command runs top only once, then gives output. i think you can do the parsing part on your own.

alpera
  • 509
  • 4
  • 9
0

one more option:

function cpuload() {
  $cont = file('/proc/stat');
  $cpuloadtmp = explode(' ',$cont[0]);
  $cpuload0[0] = $cpuloadtmp[2] + $cpuloadtmp[4];
  $cpuload0[1] = $cpuloadtmp[2] + $cpuloadtmp[4]+ $cpuloadtmp[5];
  sleep(1);
  $cont = file('/proc/stat');
  $cpuloadtmp = explode(' ',$cont[0]);
  $cpuload1[0] = $cpuloadtmp[2] + $cpuloadtmp[4];
  $cpuload1[1] = $cpuloadtmp[2] + $cpuloadtmp[4]+ $cpuloadtmp[5];
  return ($cpuload1[0] - $cpuload0[0])*100/($cpuload1[1] - $cpuload0[1]);
}