Reputation: 14820
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?
Upvotes: 5
Views: 5324
Reputation: 14820
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 %.
Upvotes: 3
Reputation: 66169
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.
Upvotes: 5