cpuusage 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/bin/sh
  2. if [ "$1" = "-h" ]; then
  3. cat <<EOF>&2
  4. Usage: ${0##*/}
  5. Return the CPU usage. Linux only.
  6. EOF
  7. exit
  8. fi
  9. if [ ! "$(uname)" = "Linux" ]; then
  10. echo >&2 "Linux only."
  11. exit 1
  12. fi
  13. ## CPU usage
  14. ##
  15. ## A typical CPU array is (on Linux Kernel 3.0)
  16. ## cpu 158150 0 52354 18562746 1472 0 10198 0 0 0
  17. ##
  18. ## The meanings of the columns are as follows, from left to right:
  19. ##
  20. ## user: normal processes executing in user mode
  21. ## nice: niced processes executing in user mode
  22. ## system: processes executing in kernel mode
  23. ## idle: twiddling thumbs
  24. ## iowait: waiting for I/O to complete
  25. ## irq: servicing interrupts
  26. ## softirq: servicing softirqs
  27. ## ... (see 'man 5 proc' for further details)
  28. ##
  29. ## Only the first 4 values are interesting here.
  30. cpuarray="$(grep '^cpu ' /proc/stat)"
  31. ## We start at field #3 since there are 2 spaces after 'cpu'.
  32. f1=$(echo "$cpuarray" | cut -f3 -d' ')
  33. f2=$(echo "$cpuarray" | cut -f4 -d' ')
  34. f3=$(echo "$cpuarray" | cut -f5 -d' ')
  35. f4=$(echo "$cpuarray" | cut -f6 -d' ')
  36. totalA=$((f1+f2+f3+f4))
  37. idleA=$f4
  38. sleep 1
  39. cpuarray="$(grep '^cpu ' /proc/stat)"
  40. f1=$(echo "$cpuarray" | cut -f3 -d' ')
  41. f2=$(echo "$cpuarray" | cut -f4 -d' ')
  42. f3=$(echo "$cpuarray" | cut -f5 -d' ')
  43. f4=$(echo "$cpuarray" | cut -f6 -d' ')
  44. totalB=$((f1+f2+f3+f4))
  45. idleB=$f4
  46. totaldiff=$((${totalB:-0}-${totalA:-0}))
  47. if [ $totaldiff -eq 0 ]; then
  48. echo 0
  49. else
  50. echo "$((100 - 100 * (idleB-idleA) / totaldiff))"
  51. fi