cpuUsage.sh 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/bin/bash
  2. function get_total_cpu_time() {
  3. # Read the first line of /proc/stat and remove the cpu prefix
  4. CPU=(`sed -n 's/^cpu\s//p' /proc/stat`)
  5. # Sum all of the values in CPU to get total time
  6. for VALUE in "${CPU[@]}"; do
  7. let $1=$1+$VALUE
  8. done
  9. }
  10. TOTAL_TIME_BEFORE=0
  11. get_total_cpu_time TOTAL_TIME_BEFORE
  12. # Loop over the arguments, which are a list of PIDs
  13. # The 13th and 14th words in /proc/<PID>/stat are the user and system time
  14. # the process has used, so sum these to get total process run time
  15. declare -a PROCESS_BEFORE_TIMES
  16. ITER=0
  17. for PID in "$@"; do
  18. if [ -f /proc/$PID/stat ]
  19. then
  20. PROCESS_STATS=`cat /proc/$PID/stat`
  21. PROCESS_STAT_ARRAY=($PROCESS_STATS)
  22. let PROCESS_TIME_BEFORE="${PROCESS_STAT_ARRAY[13]}+${PROCESS_STAT_ARRAY[14]}"
  23. else
  24. let PROCESS_TIME_BEFORE=0
  25. fi
  26. PROCESS_BEFORE_TIMES[$ITER]=$PROCESS_TIME_BEFORE
  27. ((++ITER))
  28. done
  29. # Wait for a second
  30. sleep 1
  31. TOTAL_TIME_AFTER=0
  32. get_total_cpu_time TOTAL_TIME_AFTER
  33. # Check the user and system time sum of each process again and compute the change
  34. # in process time used over total system time
  35. ITER=0
  36. for PID in "$@"; do
  37. if [ -f /proc/$PID/stat ]
  38. then
  39. PROCESS_STATS=`cat /proc/$PID/stat`
  40. PROCESS_STAT_ARRAY=($PROCESS_STATS)
  41. let PROCESS_TIME_AFTER="${PROCESS_STAT_ARRAY[13]}+${PROCESS_STAT_ARRAY[14]}"
  42. else
  43. let PROCESS_TIME_AFTER=${PROCESS_BEFORE_TIMES[$ITER]}
  44. fi
  45. PROCESS_TIME_BEFORE=${PROCESS_BEFORE_TIMES[$ITER]}
  46. let PROCESS_DELTA=$PROCESS_TIME_AFTER-$PROCESS_TIME_BEFORE
  47. let TOTAL_DELTA=$TOTAL_TIME_AFTER-$TOTAL_TIME_BEFORE
  48. CPU_USAGE=`echo "$((100*$PROCESS_DELTA/$TOTAL_DELTA))"`
  49. # Parent script reads from stdout, so echo result to be read
  50. echo $CPU_USAGE
  51. ((++ITER))
  52. done