Debian: Find out CPU usage using bash

2019-04-08 21:16发布

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?

2条回答
小情绪 Triste *
2楼-- · 2019-04-08 21:32

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

查看更多
别忘想泡老子
3楼-- · 2019-04-08 21:38

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.

查看更多
登录 后发表回答