Skip to content

Instantly share code, notes, and snippets.

@jvehent
Created October 18, 2013 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jvehent/7040980 to your computer and use it in GitHub Desktop.
Save jvehent/7040980 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# calculate the cpu usage of a single process
# jvehent oct.2013
[ -z $1 ] && echo "usage: $0 <pid>"
sfile=/proc/$1/stat
if [ ! -r $sfile ]; then echo "pid $1 not found in /proc" ; exit 1; fi
proctime=$(cat $sfile|awk '{print $14}')
totaltime=$(grep '^cpu ' /proc/stat |awk '{sum=$2+$3+$4+$5+$6+$7+$8+$9+$10; print sum}')
echo "time ratio cpu%"
while [ 1 ]; do
sleep 1
prevproctime=$proctime
prevtotaltime=$totaltime
proctime=$(cat $sfile|awk '{print $14}')
totaltime=$(grep '^cpu ' /proc/stat |awk '{sum=$2+$3+$4+$5+$6+$7+$8+$9+$10; print sum}')
ratio=$(echo "scale=2;($proctime - $prevproctime) / ($totaltime - $prevtotaltime)"|bc -l)
echo "$(date --rfc-3339=seconds); $ratio; $(echo "$ratio*100"|bc -l)"
done
@tobiaspal
Copy link

You can use simply:
while true; do
instead of
while [ 1 ]; do

@terryburton
Copy link

while true is more costly since it executes a new process, /bin/true.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment