12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- #!/bin/sh
- if [ "$1" = "-h" ]; then
- cat <<EOF>&2
- Usage: ${0##*/}
- Return the CPU usage. Linux only.
- EOF
- exit
- fi
- if [ ! "$(uname)" = "Linux" ]; then
- echo >&2 "Linux only."
- exit 1
- fi
- ## CPU usage
- ##
- ## A typical CPU array is (on Linux Kernel 3.0)
- ## cpu 158150 0 52354 18562746 1472 0 10198 0 0 0
- ##
- ## The meanings of the columns are as follows, from left to right:
- ##
- ## user: normal processes executing in user mode
- ## nice: niced processes executing in user mode
- ## system: processes executing in kernel mode
- ## idle: twiddling thumbs
- ## iowait: waiting for I/O to complete
- ## irq: servicing interrupts
- ## softirq: servicing softirqs
- ## ... (see 'man 5 proc' for further details)
- ##
- ## Only the first 4 values are interesting here.
- cpuarray="$(grep '^cpu ' /proc/stat)"
- ## We start at field #3 since there are 2 spaces after 'cpu'.
- f1=$(echo "$cpuarray" | cut -f3 -d' ')
- f2=$(echo "$cpuarray" | cut -f4 -d' ')
- f3=$(echo "$cpuarray" | cut -f5 -d' ')
- f4=$(echo "$cpuarray" | cut -f6 -d' ')
- totalA=$((f1+f2+f3+f4))
- idleA=$f4
- sleep 1
- cpuarray="$(grep '^cpu ' /proc/stat)"
- f1=$(echo "$cpuarray" | cut -f3 -d' ')
- f2=$(echo "$cpuarray" | cut -f4 -d' ')
- f3=$(echo "$cpuarray" | cut -f5 -d' ')
- f4=$(echo "$cpuarray" | cut -f6 -d' ')
- totalB=$((f1+f2+f3+f4))
- idleB=$f4
- totaldiff=$((${totalB:-0}-${totalA:-0}))
- if [ $totaldiff -eq 0 ]; then
- echo 0
- else
- echo "$((100 - 100 * (idleB-idleA) / totaldiff))"
- fi
|