What is a command line alternative to top for finding current CPU utilization that isn't dependent on screen width?
Solution 1
The sysstat package includes mpstat. Running
mpstat 2 | awk '{print $11}'
Gave me the idle-time percentage which seems like the inverse of what you want, so you might need to do a little work on mpstat output:
8 % mpstat 2 | awk '{print $11}'
%idle
100.00
99.50
100.00
100.00
100.00
100.00
I had mpstat on my Slackware 11 system, but it didn't appear on my Arch system until I did pacman -S sysstat
Solution 2
In your script, set the COLUMNS environment variable to be sufficiently high to get the output you need.
export COLUMNS=100
top -p ...
You could also change the COLUMNS var just for the top
invocation thusly:
COLUMNS=100 top -p ...
Solution 3
ps u -p <PID>
Works fine. you also might try using awk
with it:
pid=16707; ps u -p $pid --no-heading | awk -v pid=${pid} -F" " '{print "CPU usage for "$11": "$3}'
Solution 4
You could just use the f
key to adjust the columns displayed. Remove some columns and add the CPU%. You should be able to see it then.
Related videos on Youtube
![Cory Klein](https://i.stack.imgur.com/gmL3R.jpg?s=256&g=1)
Cory Klein
Updated on September 18, 2022Comments
-
Cory Klein almost 2 years
If I run
top -p <myPID> -n 1
with a terminal that isn't wide enough, the CPU utilization % is omitted from the output. When trying to find a process' cpu utilization via bash scripting, this is a huge problem, as the script won't work if the terminal you're running it in isn't wide enough.ps -oe pcpu,pid,cmd
will give me the total average cpu, but not a running utilization.Is there a command that I can use to get the current cpu utilization of a process that isn't dependent on terminal width?
-
cjm about 13 yearsHe's trying to do this from a script. As far as I can tell,
top
doesn't have a command-line option to specify columns. -
Keith about 13 yearsWell how about a Python script? Use the CPUMeasurer object from the procfs module.
-
Cory Klein about 13 yearsYea, you can't use the interactive features of
top
from a script, so this won't work. -
Cory Klein about 13 yearsThis doesn't work either. I need the current cpu utilization.
ps
just gives the total average historical utilization. -
Keith about 13 yearsMy script doesn't use top, it computes CPU utilization directly the same way top does.
-
laebshade almost 13 yearsTry this one:
top -n 1 -p 13145 | grep PID --after 1 | grep -v PID | awk -F" " '{print $1}'
-
Cory Klein almost 13 yearsI can't use top, because if the window running the shell is too narrow, top won't display the CPU info.