Bash script: write CPU utilization to file (Ubuntu) - bash

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!

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)

Related

CPU usage reporting in terminal

I am trying to get the CPU usage of a mac over time.
I am using this top cmd in terminal getting the result i want but would like it to output to a file and update every 5 seconds.
top -l 1 | grep -E "^CPU|^Phys"
CPU usage: 3.27% user, 14.75% sys, 81.96% idle
PhysMem: 5807M used (1458M wired), 10G unused.
This command prints all 3 CPU usage percentages tab-separated to a file (appending line by line for each call):
top -l1 | grep -E "CPU usage:" | awk -v FS="CPU usage: | user, | sys, | idle" '{print $2, $3, $4}' >> cpu_user_sys_idle.tsv
Works with pipe separated command chain:
Top as you suggested
Grep to filter only line with CPU usage
Awk with variable field-separator (-v FS) using either of the 4 strings to get all percentages as isolated fields. Then print second, third and fourth (omit first since it is empty).
>> redirects output appending to file (e.g. cpu_user_sys_idle.tsv)
You additionally can put it into automated or scheduled (apple)script to collect measures in regular intervals.

Get total CPU usage from the terminal on a Mac? [duplicate]

Ive seen the same question asked on linux and windows but not mac (terminal). Can anyone tell me how to get the current processor utilization in %, so an example output would be 40%. Thanks
This works on a Mac (includes the %):
ps -A -o %cpu | awk '{s+=$1} END {print s "%"}'
To break this down a bit:
ps is the process status tool. Most *nix like operating systems support it. There are a few flags we want to pass to it:
-A means all processes, not just the ones running as you.
-o lets us specify the output we want. In this case, it all we want to the cpu% column of ps's output.
This will get us a list of all of the processes cpu usage, like
0.0
1.3
27.0
0.0
We now need to add up this list to get a final number, so we pipe ps's output to awk. awk is a pretty powerful tool for parsing and operating on text. We just simply add up the numbers, then print out the result, and add a "%" on the end.
Adding up all those CPU % can give a number > 100% (probably multiple cores).
Here's a simpler method, although it comes with some problems:
top -l 2 | grep -E "^CPU"
This gives 2 samples, the first of which is nonsense (because it calculates CPU load between samples).
Also, you need to use RegEx like (\d+\.\d*)% or some string functions to extract values, and add "user" and "sys" values to get the total.
(From How to get CPU utilisation, RAM utilisation in MAC from commandline)
Building on previous answers from #Jon R. and #Rounak D, the following line prints the sum of user and system values, with the added percent. I've have tested this value and I like that it roughly tracks well with the percentages shown in the macOS Activity Monitor.
top -l 2 | grep -E "^CPU" | tail -1 | awk '{ print $3 + $5"%" }'
You can then capture that value in a variable in script like this:
cpu_percent=$(top -l 2 | grep -E "^CPU" | tail -1 | awk '{ print $3 + $5"%" }')
PS: You might also be interested in the output of uptime, which shows system load.
Building upon #Jon R's answer, we can pick up the user CPU utilization through some simple pattern matching
top -l 1 | grep -E "^CPU" | grep -Eo '[^[:space:]]+%' | head -1
And if you want to get rid of the last % symbol as well,
top -l 1 | grep -E "^CPU" | grep -Eo '[^[:space:]]+%' | head -1 | sed s/\%/\/
top -F -R -o cpu
-F Do not calculate statistics on shared libraries, also known as frameworks.
-R Do not traverse and report the memory object map for each process.
-o cpu Order by CPU usage
Answer Source
You can do this.
printf "$(ps axo %cpu | awk '{ sum+=$1 } END { printf "%.1f\n", sum }' | tail -n 1),"

How to find out uptime in minutes?

How to find out and save to file uptime on Solaris in minutes without cutting and converting it ? Is there any elegant way of doing it? Thanks for answers
Here is a reliable and accurate way to get the number of minutes since last boot on Solaris:
kstat -n system_misc |
nawk '/boot_time/ {printf("%d minutes\n",(srand()-$2)/60)}'
Under nawk, the srand() function returns the number of seconds since the epoch while the boot_time kstat statistic returns the number of seconds since the epoch at boot time. Subtracting the former from the latter gives the number of seconds, and dividing it further by 60 gives the number of minutes since last boot.
On Solaris, the uptime(1) command is just a link to w(1). You can find its source code at https://github.com/illumos/illumos-gate/blob/master/usr/src/cmd/w/w.c.
There, you will find that uptime(1) gets the boot time as recorded in /var/run/utmpx. Just as they do, you can read the data from this file using the getutxent(3) family of functions, and look for a record with ut_type == BOOT_TIME. In this record, look at the ut_tv field, which is a struct timeval and contains the seconds and microseconds of the boot time. From this you can calculate how long the system has been up.
(Edit: I just noticed the shell tag. This solution would be more suitable for calling from a C program. Oh well, maybe it will be useful to someone.)
Not completely sure that this will work on Solaris but...
uptime | awk -F ',' ' {print $1} ' | awk ' {print $3} ' | awk -F ':' ' {hrs=$1; min=$2; print hrs*60 + min} '
A small improvement on #jilliagre's suggestion is to use kstat(1m) to extract more information for you before passing to nawk(1):
$ kstat -p -n system_misc -s boot_time| nawk '{printf("%d minutes\n",(srand()-$2)/60)}'
26085 minutes
-p means "parseable output", -s selects the specific stat underneath -n module name.

How to get CPU utilization in % in terminal (mac)

Ive seen the same question asked on linux and windows but not mac (terminal). Can anyone tell me how to get the current processor utilization in %, so an example output would be 40%. Thanks
This works on a Mac (includes the %):
ps -A -o %cpu | awk '{s+=$1} END {print s "%"}'
To break this down a bit:
ps is the process status tool. Most *nix like operating systems support it. There are a few flags we want to pass to it:
-A means all processes, not just the ones running as you.
-o lets us specify the output we want. In this case, it all we want to the cpu% column of ps's output.
This will get us a list of all of the processes cpu usage, like
0.0
1.3
27.0
0.0
We now need to add up this list to get a final number, so we pipe ps's output to awk. awk is a pretty powerful tool for parsing and operating on text. We just simply add up the numbers, then print out the result, and add a "%" on the end.
Adding up all those CPU % can give a number > 100% (probably multiple cores).
Here's a simpler method, although it comes with some problems:
top -l 2 | grep -E "^CPU"
This gives 2 samples, the first of which is nonsense (because it calculates CPU load between samples).
Also, you need to use RegEx like (\d+\.\d*)% or some string functions to extract values, and add "user" and "sys" values to get the total.
(From How to get CPU utilisation, RAM utilisation in MAC from commandline)
Building on previous answers from #Jon R. and #Rounak D, the following line prints the sum of user and system values, with the added percent. I've have tested this value and I like that it roughly tracks well with the percentages shown in the macOS Activity Monitor.
top -l 2 | grep -E "^CPU" | tail -1 | awk '{ print $3 + $5"%" }'
You can then capture that value in a variable in script like this:
cpu_percent=$(top -l 2 | grep -E "^CPU" | tail -1 | awk '{ print $3 + $5"%" }')
PS: You might also be interested in the output of uptime, which shows system load.
Building upon #Jon R's answer, we can pick up the user CPU utilization through some simple pattern matching
top -l 1 | grep -E "^CPU" | grep -Eo '[^[:space:]]+%' | head -1
And if you want to get rid of the last % symbol as well,
top -l 1 | grep -E "^CPU" | grep -Eo '[^[:space:]]+%' | head -1 | sed s/\%/\/
top -F -R -o cpu
-F Do not calculate statistics on shared libraries, also known as frameworks.
-R Do not traverse and report the memory object map for each process.
-o cpu Order by CPU usage
Answer Source
You can do this.
printf "$(ps axo %cpu | awk '{ sum+=$1 } END { printf "%.1f\n", sum }' | tail -n 1),"

KSH Script to get the CPU usage

Can somebody please help me to write a KSH Script to get the CPU usage of the AIX server ?
Here I want my script to get the Current usage of CPU that time it is executed
There are a number of tools on AIX (and elsewhere) to get the current CPU usage.
nmon
On AIX (and Linux) you have nmon. This gives very detailed infos on memory, cpu usage, disk usage, etc. It is normally used as an interactive tool.
sar
call sar -u 1 1 to get the current cpu usage. See the manual page of sar for a whole lot of options. Depending on your installation you need to be root or add your user to the group "adm".
Just call w -u. It outputs a little bit more than you ask for. If you don't need that you can use awk/sed/cut to cut it away.
I use the following script in bash, but I just tried it in ksh and it works all the same:
top -bn2 | grep 'Cpu(s)' | sed -n '2s/.*, *\([0-9.]*\)%* id.*/\1/p' | awk '{print "CPU: " 100 - $1" %"}
You can also use
top -bn1 | grep 'Cpu(s)' | sed -n 's/.*, *\([0-9.]*\)%* id.*/\1/p' | awk '{print "CPU: " 100 - $1" %"}'
for faster response, but the result will be less accurate.

Resources