#!/bin/sh
#
# Cheap-o sequential read-write test script using "dd".
#
# Placed into the public domain in 2002
# by the author, Curt Sampson <cjs@cynic.net>.
#

# Number of seconds to wait between initial sync and starting the
# test, in order to give the disk system time to settle down.
#
prewait=30		

# Where I store my vmstat data.
#
vmstat_tmp=/tmp/vmstat.$$

########################################
# Parse arguments

count=$1
bs=$2
mb=$3

if [ ! "$mb" -gt 0 ]; then
    echo "usage: disktest1 <num-writers> <blocksizeKB> <MB-per-writer>"
    exit 2
fi


########################################
# Write test

sync; sync; sleep $prewait;		# Give disks time to settle down.

waitlist=""
starttime=`date +%s`
i=0; while [ $i -lt $count ]; do
    i=$(($i+1))
    dd if=/dev/zero of=file$i bs=${bs}k count=$((1024*${mb}/${bs})) 2>/dev/null &
    waitlist="$waitlist $!"
done
vmstat -w 1 > $vmstat_tmp & vmstat_pid=$!
wait $waitlist; kill $vmstat_pid; sync; sync
endtime=`date +%s`

avgcpu=`tail +5 $vmstat_tmp | grep -v '[a-z]' |
    awk '{ count+=1; total+=100-$NF } END { print int(total/count) }'`
rm $vmstat_tmp

totaltime=$(($endtime-$starttime))
totalmb=$(($count*$mb))
mbsec=`echo "scale=2\n$totalmb/$totaltime" | bc`

echo "$count writers ${bs}K blocks aggregate $totalmb MB" \
    "in $totaltime : $mbsec MB/sec $avgcpu %CPU";


########################################
# Read test

sync; sync; sleep $prewait;		# Give disks time to settle down.

starttime=`date +%s`
i=0; while [ $i -lt $count ]; do
    i=$(($i+1))
    dd if=file$i of=/dev/null bs=${bs}k &
    waitlist="$waitlist $!"
done
vmstat -w 1 > $vmstat_tmp & vmstat_pid=$!
wait $waitlist; kill $vmstat_pid; sync; sync
endtime=`date +%s`

avgcpu=`tail +5 $vmstat_tmp | grep -v '[a-z]' |
    awk '{ count+=1; total+=100-$NF } END { print int(total/count) }'`
rm $vmstat_tmp

totaltime=$(($endtime-$starttime))
totalmb=$(($count*$mb))
mbsec=`echo "scale=2\n$totalmb/$totaltime" | bc`

echo "$count readers ${bs}K blocks aggregate $totalmb MB" \
    "in $totaltime : $mbsec MB/sec $avgcpu %CPU";


########################################
# Clean up

i=0; while [ $i -lt $count ]; do i=$((i+1)); rm file$i; done
sync; sync;
