#!/usr/bin/gawk -f
#-------------------------------------------------------------------------------
# ~/bin/cpustat :   display cpu utilization
#
# usage         :   normally used as a GNU/screen backtick
#
# notes         :   1. Works on the assumption that /proc/stat's first line
#               :      has the total "jiffies" since boot up used by the
#               :      different types of tasks in the system. See the
#               :      filesystems/proc.txt document in kernel source tree
#               :
#               :   2. Displays a total CPU% (user+system+nice) as well as
#               :      user CPU% system CPU% and nice CPU%
#-------------------------------------------------------------------------------
BEGIN {
  file = "/proc/stat"
  while (getline < file) {                        # read first line
                                                  # extract jiffies:
      user=$2-user_saved;                         # . user
      nice=$3-nice_saved;                         # . nice user
      syst=$4-syst_saved;                         # . system
      idle=$5-idle_saved;                         # . idle
      wait=$6-wait_saved;                         # . iowait
      irqs=$7-irqs_saved;                         # . irq
      sirq=$8-sirq_saved;                         # . softirq

      cact=user+syst+nice;                        # what counts
      ctot=user+nice+syst+idle+wait+irqs+sirq;    # total activity

      tcpu=cact/ctot*100;                         # total  % cpu utilization
      ucpu=user/ctot*100;                         # user   % cpu utilization
      scpu=syst/ctot*100;                         # system % cpu utilization
      ncpu=nice/ctot*100;                         # nice   % cpu utilization

      printf "%.1f %%\n",tcpu


      user_saved=$2;                              # save the current jiffies
      nice_saved=$3;                              # values for the next loop
      syst_saved=$4;
      idle_saved=$5;
      wait_saved=$6;
      irqs_saved=$7;
      sirq_saved=$8;

      close(file)                                 # re-read file

      system("sleep 3")
    }
}