Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debian: Find out CPU usage using bash

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?

like image 863
bytecode77 Avatar asked Mar 23 '12 16:03

bytecode77


People also ask

How do I see exact CPU usage in Linux?

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.

How do I check my CPU using top command?

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.


2 Answers

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.

like image 134
AD7six Avatar answered Sep 30 '22 13:09

AD7six


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

like image 22
bytecode77 Avatar answered Sep 30 '22 15:09

bytecode77