Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mean running time over a number of runs

Tags:

bash

I would like to report the mean running time (computed using the time command) of a script after running it, say, n times. Is there a simple bash command, script, or system utility that I'm unaware of and that would allow me to do that?

like image 753
Anthony Labarre Avatar asked Dec 13 '22 07:12

Anthony Labarre


1 Answers

This is an interesting question so I took a few minute and wrote a script for it. Below is the light version of the script which takes in a file that has the output of running the time command. The full script has many more options and takes in a command directly to run averages on directly.

Code:

#!/bin/bash
# calculate the mean average of wall clock time from multiple /usr/bin/time results.

file=${1}
cnt=0

if [ ${#file} -lt 1 ]; then
    echo "you must specify a file containing output of /usr/bin/time results"
    exit 1
elif [ ${#file} -gt 1 ]; then
    samples=(`grep --color=never  real ${file} | awk '{print $2}' | cut -dm -f2 | cut -ds -f1`)

    for sample in `grep --color=never real ${file} | awk '{print $2}' | cut -dm -f2 | cut -ds -f1`; do
        cnt=$(echo ${cnt}+${sample} | bc -l)
    done

    # Calculate the 'Mean' average (sum / samples).
    mean_avg=$(echo ${cnt}/${#samples[@]} | bc -l)
    mean_avg=$(echo ${mean_avg} | cut -b1-6)

    printf "\tSamples:\t%s \n\tMean Avg:\t%s\n\n" ${#samples[@]} ${mean_avg}
fi 

Example (here I named the script timeit.sh and chmod 775 timeit.sh and chown jon timeit.sh*):

[ 09:22 [email protected] ~ ]$ /usr/bin/time -a -o times.log -p sleep 3
[ 09:23 [email protected] ~ ]$ /usr/bin/time -a -o times.log -p sleep 1
[ 09:23 [email protected] ~ ]$ /usr/bin/time -a -o times.log -p sleep 2
[ 09:23 [email protected] ~ ]$ /usr/bin/time -a -o times.log -p sleep 2
[ 09:23 [email protected] ~ ]$ /usr/bin/time -a -o times.log -p sleep 7
[ 09:23 [email protected] ~ ]$ /usr/bin/time -a -o times.log -p sleep 0.5
[ 09:23 [email protected] ~ ]$ ./timeit.sh times.log
        Samples:        6
        Mean Avg:       2.5833

[ 09:23 [email protected] ~ ]$ cat times.log
real 3.00
user 0.00
sys 0.00
real 1.00
user 0.00
sys 0.00
real 2.00
user 0.00
sys 0.00
real 2.00
user 0.00
sys 0.00
real 7.00
user 0.00
sys 0.00
real 0.50
user 0.00
sys 0.00

*chown isnt necessary here, but I couldn't help it! :)

man time:

Syntax
time [option...] command [arg...]

Options

-o FILE --output=FILE
Write the resource use statistics to FILE.

-a --append
Append the resource use information to the output file instead of overwriting it.

-o FILE --output=FILE
Write the resource use statistics to FILE. By default, this overwrites the file, destroying the file's previous contents.

-p --portability
Use the POSIX format.

like image 175
chown Avatar answered Dec 20 '22 15:12

chown