I'm using PHP to read the current CPU usage. I'm on a vServer, so shell_exec is enabled.
I have tried grep
on ps
, but it didn't work.
How can I read the current % CPU usage using bash?
Check CPU Usage with vmstat Command The vmstat command will display the information about system processes, memory, swap, I/O, and CPU performance. It will display the average details since the last reboot. Press CTRL+C to close the vmstat.
The top command calculates the elapsed CPU time since the last screen update, expressed as a percentage of total CPU time. For example, suppose we set two seconds as the refresh interval, and the CPU usage reports 50% after a refresh.
The easiest way is simply to use sys_getloadavg
If you want to directly ask the OS, use uptime
$uptimeString = `uptime`;
Or any of the existing answers to how to do exactly the same thing in bash and just wrap in backticks.
After taking a closer look at all solutions, I came up with this code:
<?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);
?>
It calls ps -aux
and sums up the CPU %.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With