Show CPU usage using a command

117,389

Solution 1

To get cpu usage, best way is to read /proc/stat file. See man 5 proc for more help.

There is a useful script written by Paul Colby i found here

#!/bin/bash
# by Paul Colby (http://colby.id.au), no rights reserved ;)

PREV_TOTAL=0
PREV_IDLE=0

while true; do

  CPU=(`cat /proc/stat | grep '^cpu '`) # Get the total CPU statistics.
  unset CPU[0]                          # Discard the "cpu" prefix.
  IDLE=${CPU[4]}                        # Get the idle CPU time.

  # Calculate the total CPU time.
  TOTAL=0

  for VALUE in "${CPU[@]:0:4}"; do
    let "TOTAL=$TOTAL+$VALUE"
  done

  # Calculate the CPU usage since we last checked.
  let "DIFF_IDLE=$IDLE-$PREV_IDLE"
  let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
  let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"
  echo -en "\rCPU: $DIFF_USAGE%  \b\b"

  # Remember the total and idle CPU times for the next check.
  PREV_TOTAL="$TOTAL"
  PREV_IDLE="$IDLE"

  # Wait before checking again.
  sleep 1
done

save it to cpu_usage, add execute permission chmod +x cpu_usage and run:

./cpu_usage

to stop the script, hit Ctrl+c

Solution 2

Why not use htop [interactive process viewer]? In order to install it, open a terminal window and type:

sudo apt-get install htop

Also see man htop for more information and how to set it up.

enter image description here enter image description here

Solution 3

I found a solution which works nicely, here it is:

top -bn2 | grep '%Cpu' | tail -1 | grep -P  '(....|...) id,' 

I am not sure but it looks to me that the first iteration of top with the -n parameter returns some dummy data, always the same in all my tests.

If I use -n2 then the second frame is always dynamic. So the sequence is:

  1. Get the 2 first frames of top: top -bn2
  2. Then from those frames take only the lines that contain '%Cpu': grep '%Cpu'
  3. Then only take the last occurrence/line: `tail -1``
  4. Then get the idle value ( has 4 or 5 chars, a space, "id,"): grep -P '(....|...) id,'

Hope it helps, Paul

enter image description here

Share:
117,389

Related videos on Youtube

Morteza Soltanabadiyan
Author by

Morteza Soltanabadiyan

Updated on September 18, 2022

Comments

  • Morteza Soltanabadiyan
    Morteza Soltanabadiyan over 1 year

    I want to see CPU usage.
    I used this command :

    top -bn1 | grep "Cpu(s)" | 
               sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | 
               awk '{print 100 - $1}'
    

    But it returns 100%.
    What's the correct way?

  • Fidel Pérez Menéndez
    Fidel Pérez Menéndez about 6 years
    Not really "dummy data", but yes, the first iteration of top has no previous sample to compare its data to, hence the apparent nonsense. See this comment.
  • Himanshu Bansal
    Himanshu Bansal over 4 years
    its always showing 0% on tx.2large EC2 instance. What's the issue? while the cloudwatch showing 23%