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.
In addition to the answer below, you have another option here: https://stackoverflow.com/q/54920113
– hkotsubo