Get cpu percent usage in php
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']
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%