Search code examples
linuxcommand-lineterminalubuntu-14.04

overall CPU usage and Memory(RAM) usage in percentage in linux/ubuntu


I want to findout overall CPU usage and RAM usage in percentage, but i dint get success

$ command for cpu usage
4.85%

$ command for memory usage
15.15%

OR

$ command for cpu and mamory usage
cpu: 4.85%
mem: 15.15%

How can I achieve this?


Solution

  • You can use top and/or vmstat from the procps package. Use vmstat -s to get the amount of RAM on your machine (optional), and then use the output of top to calculate the memory usage percentages.

    %Cpu(s):  3.8 us,  2.8 sy,  0.4 ni, 92.0 id,  1.0 wa,  0.0 hi,  0.0 si,  0.0 st
    KiB Mem : 24679620 total,  1705524 free,  7735748 used, 15238348 buff/cache
    KiB Swap:        0 total,        0 free,        0 used. 16161296 avail Mem 
    

    You can also do this for relatively short output:

    watch '/usr/bin/top -b | head -4 | tail -2'

    A shell pipe that calculates the current RAM usage periodically is

    watch -n 5 "/usr/bin/top -b | head -4 | tail -2 | perl -anlE 'say sprintf(\"used: %s   total: %s  => RAM Usage: %.1f%%\", \$F[7], \$F[3], 100*\$F[7]/\$F[3]) if /KiB Mem/'"
    

    (CPU + Swap usages were filtered out here.)

    This command prints every 5 seconds:

    Every 5.0s: /usr/bin/top -b | head -4 | tail -2 | perl -anlE 'say sprintf("u...  wb3: Wed Nov 21 13:51:49 2018
    
    used: 8349560   total: 24667856  => RAM Usage: 33.8%