What are the methods available to get the CPU usage in Linux Command line? [closed]
Solution 1:
As others have said, the best way is probably top
. It needs a little tweaking and a little parsing but you can get it to give you the current CPU use as a percentage.
top
splits CPU usage between user, system processes and nice
processes, we want the sum of the three. So, we can run top
in b
atch mode which allows us to parse its output. However, as explained here, the 1st iteration of top -b
returns the percentages since boot, we therefore need at least two iterations (-n 2
) to get the current percentage. To speed things up, you can set the d
elay between iterations to 0.01
. Finally, you grep
the line containing the CPU percentages and then use gawk
to sum user, system and nice processes:
top -bn 2 -d 0.01 | grep '^%Cpu' | tail -n 1 | gawk '{print $2+$4+$6}'
----- ------ ----------- --------- ----------------------
| | | | |------> add the values
| | | |--> keep only the 2nd iteration
| | |----------------> keep only the CPU use lines
| |----------------------------> set the delay between runs
|-----------------------------------> run twice in batch mode
I thought you could also get this information through ps -o pcpu ax
by adding the %use of each running process. Unfortunately, as explained here, ps
"returns the percentage of time spent running during the entire lifetime of a process" which is not what you need.
EDIT
Based on your comment, your version of top
is different to mine and you should use this instead:
top -bn 2 -d 0.01 | grep '^Cpu.s.' | tail -n 1 | gawk '{print $2+$4+$6}'
And, to avoid issues with localization, set the locale to C:
LC_ALL=C top -bn 2 -d 0.01 | grep '^Cpu.s.' | tail -n 1 | gawk '{print $2+$4+$6}'
Solution 2:
sar
is the definitive way to do it. So for instance sar -u
will output something like this:
08:30:01 AM CPU %user %nice %system %iowait %idle
08:40:01 AM all 6.94 0.00 1.77 4.92 86.36
08:50:01 AM all 5.73 0.00 2.31 12.72 79.24
09:00:01 AM all 5.95 0.00 2.58 18.36 73.11
09:10:01 AM all 6.88 0.00 2.22 17.44 73.45
09:20:01 AM all 8.61 0.00 2.68 27.93 60.78
You don't say which Linux you use but for CentOS/RedHat you need to install the sysstat
package, and I think it's the same on Debian/Ubuntu.
You can also use sar to gather statistics ad hoc:
sar -o /tmp/sar.out 60 600
Will gather stats every 60 seconds 600 times, so 600 minutes.