5

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?

bytecode77
  • 14,163
  • 30
  • 110
  • 141
  • would load average from bash suffice? `cat /proc/loadavg` also, http://www.cyberciti.biz/tips/how-do-i-find-out-linux-cpu-utilization.html (sysstat) may be something you might want to use/install. – TryTryAgain Mar 23 '12 at 16:08

2 Answers2

5

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.

Community
  • 1
  • 1
AD7six
  • 63,116
  • 12
  • 91
  • 123
  • I've seen the getLoadAvg commande before, but it's not the same as CPU usage (%). Both uptime and getloadavg could be interesting, too. But how can I find out the CPU usage? – bytecode77 Mar 23 '12 at 17:29
  • have you read the existing answers - e.g. the first answer in the question I linked to? – AD7six Mar 23 '12 at 18:16
  • Oh wait a moment. It always shows the same values, except if I wait for a few seconds. My PHP script always reads the same values... – bytecode77 Mar 23 '12 at 18:56
3

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 %.

bytecode77
  • 14,163
  • 30
  • 110
  • 141