Bootstrap FreeKB - Linux Commands - List the amount of memory and CPU used using the top command
Linux Commands - List the amount of memory and CPU used using the top command

Updated:   |  Linux Commands articles

By default, the top command can be used to view processes in real time, meaning that the top output will refresh every few seconds.

[root@server1 ]# top
top - 21:46:14 up 2 days, 29 min, 2 users, load average: 0.31, 0.40, 0.54
Tasks 160 total, 1 running, 158 sleeping, 0 stopped, 0 zombie
%Cpu(s): 4.5 us, 2.2 sy, 1.5 ni, 90.0 id, 4.8 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem:  3067824 total, 1498976 used, 1560456 free, 54168 buffers
KiB Swap: 3104837 total,       0 used, 3104872 free, 85747 cached Mem

PID    User   PR  NI     VIRT     RES     SHR   S  %CPU  %MEM    TIME+   COMMANDS
4594   root   20   0   417768  144754    5803   S   6.0   5.2  0:41:49       Xorg
2488   User1  20   0    92281   85793   84739   S   3.3   4.5  1:04:77 gnome-term
3794   User1  20   0   144384  209193   48473   S   5.7   3.2  0:32:99    firefox
. . .

 

The -n 1 option can be used to display a snap shot of top.

top -n 1

 

By default, top will only return the results that fit the current console window. The -b (batch) flag can be used to return the full top output.

top -b -n 1

 

Additionally, the -o option can be used to sort the output on a specific column. In this example, the output will be sorted on the %CPU column (which is the default anyways).

top -b -n 1 -o %CPU

 

If you need to capture the CPU over a period of time, such as over a 24 hour period, a script could be invoked once every minute, where the script outputs the overall CPU average to a file. In this example, a BASH shell script will output the CPU average to a file named cpu.txt.

#!/bin/bash
IFS=$'\n'
datetime=$(date '+%Y%m%d.%H%M%S')

lines=$(top -b -n 1 -o %CPU | egrep -v ^'(Tasks|%Cpu|KiB|top|  PID)' | sed '/^$/d')

echo | tee --append cpu.txt

for line in $lines; do
        cpu=$(echo $line | awk '{print $9}')
        if [ $cpu != '0.0' ]; then
                echo [$datetime] $line | tee --append cpu.txt
        fi
done

echo | tee --append cpu.txt

unset IFS

 

This script could then be scheduled to run once every minute via a crontab job, something like this.

* * * * * bash /path/to/cpu.sh

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 16596f in the box below so that we can be sure you are a human.