How to get the runtime of a program with shell script?

0

I am creating a basic script in which I would like to get the runtime of a program each time it is called in the script.

#!/bin/bash

for i in {1..15}
do
 echo "Execucao $i"
 time ./meu_programa > resultados_nesse_arquivo.txt
done

But when I run this script, I get only the standard output from my program, how can I get a similar result like:

 Execucao X

 real    0m0,001s
 user    0m0,001s
 sys     0m0,000s
    
asked by anonymous 04.03.2018 / 17:51

1 answer

2

This is because time sends the result to stderr instead of stdout by default.

You just need to redirect the output.

Example:

#!/bin/bash

outfile="benchmark.txt"

for i in $(seq 1 15)
do
    echo "Execução: $i" >> $outfile
    echo "-----------------" >> $outfile
    (time cat arquivo.txt) >> $outfile 2>&1
    echo "" >> $outfile
done

Output file:

Execução: 1
-----------------
teste1
teste2

real    0m0,003s
user    0m0,003s
sys     0m0,000s

Execução: 2
-----------------
teste1
teste2

real    0m0,003s
user    0m0,004s
sys     0m0,000s

Execução: 3
-----------------
teste1
teste2

real    0m0,003s
user    0m0,003s
sys     0m0,000s

...
    
04.03.2018 / 20:53