BJPrim
BJPrim

Reputation: 358

Bash script: write CPU utilization to file (Ubuntu)

I would like to write a bash script that writes the current CPU utilization to a file "logfile". I am using Intel® Core™ i7-4500U CPU @ 1.80GHz × 4 and Ubuntu 15.10.

I have seen similar questions asked already in this forum, however not all of my questions were answered to 100 percent. By my research I came up with two possible ways of achieving my goal. First one is

    mpstat | grep "all" | awk '{ print $3 + $5; }' >> logfile

(adding user CPU and system CPU) and my second candidate is

   mpstat | grep "all" | awk '{ print 100 - $12; }' >> logfile

(100 - %idle CPU). Which one of those two is the right one for me if I am interested in the total CPU utilization (so all components that count in some form as CPU should be included).

Another question: By what I have learned by reading other threads, I think my second candidate

   mpstat | grep "all" | awk '{ print 100 - $12; }' >> logfile

should be quite accurate. However, when I open the "System Monitor" and monitor the "CPU History" I observe significantly different CPU utilization. Another thing is that the values in the System Monitor are very dynamic (CPU varies between 4% and 18%) whereas over the same period the outcome of the second command remains almost constant. Has someone an explanation for that?

Many thanks for all comments!

Upvotes: 1

Views: 2377

Answers (1)

Daniel Gray
Daniel Gray

Reputation: 1802

This happens because mpstat's first line shows an average value calculated since the system booted (which will be much more "stable" - will tend to change less and less as time goes by ).

Quote from mpstat man page:

The interval parameter specifies the amount of time in seconds between each report. A value of 0 (or no parameters at all) indicates that processors statistics are to be reported for the time since system startup (boot).

If you add an interval parameter, you will start to get back live numbers, which should more closely match your System Monitor output (try executing mpstat 1 vs. the plain mpstat).

Therefore, this Bash line should do the trick:

mpstat 1 1 | grep "all" | awk '{ print 100 - $NF; exit; }' >> logfile

and, to do it without grep (saving the extra process spawn):

mpstat 1 1 | awk '/all/{ print 100 - $NF; exit; }' >> logfile

(changed $12 to $NF for the case when the first line has a time and shifts the arguments over; with $NF we consistently get the last value, which is the idle value)

Upvotes: 2

Related Questions