You are not logged in.

#1 2009-11-24 22:07:13

graysky
Wiki Maintainer
From: :wq
Registered: 2008-12-01
Posts: 10,597
Website

some help with bash script - need to get cpu usage as a percentage

I'm writing a bash script to log some selection from a sensors output (core temp, mb temp, etc.) and I would also like to have the current cpu usage as a percentage.  I have no idea how to go about getting it in a form that a bash script can use.  For example, I would simply look in the output of htop, but again, I need to assign the % load to a variable in a bash script.

Does anyone know how I can do it?


CPU-optimized Linux-ck packages @ Repo-ck  • AUR packagesZsh and other configs

Offline

#2 2009-11-24 22:35:34

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: some help with bash script - need to get cpu usage as a percentage

'vmstat | cut -c 72-74 > log' will get you the cpu_idle%. Do you mean sth like that? it may work, but what about 100% (3 digits instead of 2)?

Offline

#3 2009-11-24 23:41:26

Procyon
Member
Registered: 2008-05-07
Posts: 1,819

Re: some help with bash script - need to get cpu usage as a percentage

It looks like vmstat is a total since the beginning, not of the last x minutes or something useful.

You need to run a program that monitors the time stats in /proc/stat, and logs the difference since the last iteration (this is what e.g. htop does) in a file, which you can then open when you need it in your script. Otherwise the script would have to be running for at least "some" interval.

Continuous script: (output it to a file and get the last results with tail -n 1)

while true; do eval $(awk '/^cpu /{print "idle=" $5 "; total=" $2+$3+$4+$5 }' /proc/stat); intervaltotal=$((total-${prevtotal:-0})); echo "$((100*( (intervaltotal) - ($idle-${previdle:-0}) ) / (intervaltotal) ))"; previdle=$idle; prevtotal=$total; sleep 5; done

Slow single percentage:

eval $(awk '/^cpu /{print "previdle=" $5 "; prevtotal=" $2+$3+$4+$5 }' /proc/stat); sleep 0.4; eval $(awk '/^cpu /{print "idle=" $5 "; total=" $2+$3+$4+$5 }' /proc/stat); intervaltotal=$((total-${prevtotal:-0})); echo "$((100*( (intervaltotal) - ($idle-${previdle:-0}) ) / (intervaltotal) ))"

Try to make sleep 0.4 as high as possible, at least.

Last edited by Procyon (2009-11-24 23:41:59)

Offline

#4 2009-11-25 03:32:52

Gen2ly
Member
From: Sevierville, TN
Registered: 2009-03-06
Posts: 1,529
Website

Re: some help with bash script - need to get cpu usage as a percentage

Very nice Procyon.


Setting Up a Scripting Environment | Proud donor to wikipedia - link

Offline

#5 2009-11-25 08:58:32

graysky
Wiki Maintainer
From: :wq
Registered: 2008-12-01
Posts: 10,597
Website

Re: some help with bash script - need to get cpu usage as a percentage

I'll give this a try.  Thanks!


CPU-optimized Linux-ck packages @ Repo-ck  • AUR packagesZsh and other configs

Offline

Board footer

Powered by FluxBB