Shell Script to calculate average runtime

Asked

Viewed 167 times

2

I need to perform the same command 10 times and view the average run time.

I did the script below, but it always returns the same output, zero, see print below.

Could you help me find the error? Apparently the sum total=$((total+time)) not being successfully performed.

Code

#!/bin/bash

TIMEFORMAT=%R
total=0
for i in $(seq 1 10); do

    time=$(time openssl enc -aes-256-cbc -salt -in 1mbfile.txt -out outs/out$i.enc -pass file:private.pem)
    total=$((total+time))
done

avg=$((total/10))
printf "Avg Time: %.4f\n" $avg

Exit

inserir a descrição da imagem aqui

  • In addition to the answer below, you have another option here: https://stackoverflow.com/q/54920113

1 answer

4


From what I read around (here, here, here, etc), bash arithmetic is limited to integers. For floating point numbers, it is necessary to use other commands or utilities.

One option is to use bc:

#!/bin/bash
TIMEFORMAT=%R
total=0
for i in $(seq 1 10); do
    time=$({ time seu-comando-aqui &>/dev/null; } 2>&1)
    total=$(echo "scale=4;$total + $time" | bc)
done

avg=$(echo "scale=4;$total / 10" | bc)
printf "Avg Time: %.4f\n" $avg

The direction to /dev/null is so that the output of the command is not part of the variable time, and later we caught the error output (stderr) and direct to the standard output (stdout) - that’s what the 2>&1 means. I did it because the time, by default, sends your output to the stderr. This caused another problem in your script, because the variable time was empty (although the output of this was shown on the console).

Because of this, the times are no longer shown, but if you want, just put a echo $time within the for.

At last, I use bc to make the calculations, using the option scale indicating the maximum number of decimal places to be taken into account in the calculation.

  • 1

    It worked perfectly! Thanks @hkotsubo

Browser other questions tagged

You are not signed in. Login or sign up in order to post.