usedcpu 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/env bash
  2. PREV_TOTAL=0
  3. PREV_IDLE=0
  4. cpuFile="/tmp/.cpu"
  5. if [[ -f "${cpuFile}" ]]; then
  6. fileCont=$(cat "${cpuFile}")
  7. PREV_TOTAL=$(echo "${fileCont}" | head -n 1)
  8. PREV_IDLE=$(echo "${fileCont}" | tail -n 1)
  9. fi
  10. CPU=(`cat /proc/stat | grep '^cpu '`) # Get the total CPU statistics.
  11. unset CPU[0] # Discard the "cpu" prefix.
  12. IDLE=${CPU[4]} # Get the idle CPU time.
  13. # Calculate the total CPU time.
  14. TOTAL=0
  15. for VALUE in "${CPU[@]:0:4}"; do
  16. let "TOTAL=$TOTAL+$VALUE"
  17. done
  18. if [[ "${PREV_TOTAL}" != "" ]] && [[ "${PREV_IDLE}" != "" ]]; then
  19. # Calculate the CPU usage since we last checked.
  20. let "DIFF_IDLE=$IDLE-$PREV_IDLE"
  21. let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
  22. let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"
  23. if [[ $1 = "-i" ]]; then
  24. echo " ${DIFF_USAGE}%"
  25. else
  26. echo "${DIFF_USAGE}%"
  27. fi
  28. else
  29. if [[ $1 = "-i" ]]; then
  30. echo " ?"
  31. else
  32. echo "?"
  33. fi
  34. fi
  35. # Remember the total and idle CPU times for the next check.
  36. echo "${TOTAL}" > "${cpuFile}"
  37. echo "${IDLE}" >> "${cpuFile}"