#!/bin/ksh -p # stopwatch - Track system-wide CPU utilization # # Tim.Cook@sun.com, 10 Mar 2008 # # SYNOPSIS # file=`stopwatch start` # At the start of an experiment # stopwatch $file # At the end # # DESCRIPTION # The first form will make the script save system utilization # numbers in a temp file, and output the file name. The second # form makes it report system utilization using the same numbers, # then delete the file. DIR=${0%/*} PROG=${0##*/} PATH=/usr/bin:/usr/sbin export PATH #------------------------------------------------------------------------ # div_cent - Decimal (to hundredths) division # # The result is put into the variable "div_cent_result" div_cent () { _dividend=$1 _divisor=$2 _quotient_int=$(( $_dividend / $_divisor )) _remainder=$(( $_dividend % $_divisor )) _cents=$(( $_remainder * 100 / $_divisor )) if [ $_cents -lt 10 ]; then div_cent_result="$_quotient_int.0$_cents" else div_cent_result="$_quotient_int.$_cents" fi } if [[ $# -ne 1 ]]; then echo "usage: $PROG { start | }" fi case $1 in 'start' ) tmpfile=`mktemp /tmp/stopwatch.XXXXXX` echo $tmpfile vmstat -s > $tmpfile ;; '/tmp/stopwatch.'* ) if [[ ! -r "$1" ]]; then echo "$PROG: can not read $1" >&2 exit 1 fi usr_end=0 sys_end=0 idl_end=0 #-- Get the end values vmstat -s | while read value a b do case "$a $b" in 'user cpu' ) usr_end=$value ;; 'system cpu' ) sys_end=$value ;; 'idle cpu' ) idl_end=$(( $idl_end + $value )) ;; 'wait cpu' ) idl_end=$(( $idl_end + $value )) ;; esac done #-- Get the deltas idl_start=0 while read value a b do case "$a $b" in 'user cpu' ) usr=$(( $usr_end - $value )) ;; 'system cpu' ) sys=$(( $sys_end - $value )) ;; 'idle cpu' ) idl_start=$(( $idl_start + $value )) ;; 'wait cpu' ) idl_start=$(( $idl_start + $value )) ;; esac done < "$1" rm -f "$1" idl=$(( $idl_end - $idl_start )) ela=$(( $usr + $sys + $idl )) div_cent $(( $usr * 100 )) $ela ; usr_pct=$div_cent_result div_cent $(( $sys * 100 )) $ela ; sys_pct=$div_cent_result div_cent $(( $idl * 100 )) $ela ; idl_pct=$div_cent_result echo "Utilization during period: " \ "${usr_pct}% usr, ${sys_pct}% sys, ${idl_pct}% idl" ;; esac