File: cpu.sh

package info (click to toggle)
awesome-extra 2012061101
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 976 kB
  • ctags: 562
  • sloc: sh: 79; awk: 18; makefile: 11
file content (50 lines) | stat: -rwxr-xr-x 1,147 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/bin/bash
# by Paul Colby (http://colby.id.au), no rights reserved ;)

# change this with your temporary files
TMP1="/dev/shm/tmp/cpuusage.total"
TMP2="/dev/shm/tmp/cpuusage.idle"

if [ ! -s "$TMP1" ]; then
	touch "$TMP1"
	echo 0 > "$TMP1"
fi

if [ ! -s "$TMP2" ]; then
	touch "$TMP2"
	echo 0 > "$TMP2"
fi

#PREV_TOTAL=0
#PREV_IDLE=0


#while true; do
  PREV_TOTAL=`cat ${TMP1}`
  PREV_IDLE=`cat ${TMP2}`

  CPU=(`cat /proc/stat | grep '^cpu '`) # Get the total CPU statistics.
  unset CPU[0]                          # Discard the "cpu" prefix.
  IDLE=${CPU[4]}                        # Get the idle CPU time.

  # Calculate the total CPU time.
  TOTAL=0
  for VALUE in "${CPU[@]}"; do
    let "TOTAL=$TOTAL+$VALUE"
  done

  # Calculate the CPU usage since we last checked.
  let "DIFF_IDLE=$IDLE-$PREV_IDLE"
  let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
  let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"
  echo -n "$DIFF_USAGE"

  # Remember the total and idle CPU times for the next check.
  #PREV_TOTAL="$TOTAL"
  #PREV_IDLE="$IDLE"
  echo $TOTAL > "$TMP1"
  echo $IDLE > "$TMP2"

  # Wait before checking again.
#  sleep 1
#done