I want to calculate in bash the average time spent by several commands. The output of time command is min:sec.milisec.
I don’t know how to add two outputs of this kind in bash and in final to calculate the average.
I tried to convert the output with date but the output is “date: invalid date `0:01.00′”.
This is a three part answer
Part one
First, use the
TIMEFORMATvariable to output only seconds elapsed. Then you can add this directlyFrom
man bashHere is an example which outputs only seconds with a precision of 0, i.e. no decimal point. Read part three why that’s important.
Part two
Second, how do we capture the output of
time? It’s actually a bit tricky, here’s how you do capture the time from the command abovePart three
How do we add the times together and get the average?
In bash we use the
$(( ))construct to do math. Note thatbashdoes not natively support floating point so you will be doing integer division (hence the precision 0.) Here is a script that will capture thetimefrom two commands and output each of the individual times and their averageOutput
If integer division is a non-starter for you and you want precision, as long as you don’t mind calling the external binary
bc, you can do this quite easily.Output