Demo entry 105122

Bash time comparison script

   

Submitted by Gulshan on Aug 30, 2013 at 05:26
Language: Bash. Code size: 1.2 kB.

#!/bin/bash

prog1=$1
prog2=$2
num_times=${3:-10}

calculate_mean() {
    sum=0
    for n in $@; do
	sum=$(($sum+$n))
    done

    echo $(echo "scale=2;$sum/$#" | bc -l)
}

calculate_sd() {
    mean=$1
    sum=0
    shift
    for n in $@; do
	sd=$(echo "$sum + ($n - $mean)^2" | bc -l)
    done

    echo $(echo "scale=2;sqrt($sd)" | bc -l)
}

calculate_time() {
    minutes=$((${1:0:1} + ${1:9:1}))
    seconds=$((${1:2:1} + ${1:11:1}))
    milliseconds=$((10#${1:4:3} + 10#${1:13:3}))
    result=$((${minutes}*60*1000 + ${seconds}*1000 + ${milliseconds}))
    echo $result
}

for i in $(eval echo {0..$num_times}); do
    time1=`(time ./${prog1} > /dev/null) 2>&1 | awk '/sys|user/{ print $2 }'`
    time2=`(time ./${prog2} > /dev/null) 2>&1 | awk '/sys|user/{ print $2 }'`
    times1[$i]=`calculate_time "$time1"`
    times2[$i]=`calculate_time "$time2"`
done

mean1=`calculate_mean ${times1[@]}`
mean2=`calculate_mean ${times2[@]}`

sd1=`calculate_sd $mean1 ${times1[@]}`
sd2=`calculate_sd $mean2 ${times2[@]}`

echo ${times1[@]}
echo ${times2[@]}

echo "Mean 1: $mean1"
echo "Mean 2: $mean2"

echo "SD 1: $sd1"
echo "SD 2: $sd2"

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).