Primal Pappachan
Primal Pappachan

Reputation: 26525

Shell script to calculate time elapsed

I was trying to write a script to execute a C program and measure the time for execution using time command in Unix.

The script looks like follows

cc /home/pop/Daa/abc.c 

r = `time /home/pop/Daa/./a.out`

echo "recursion" $r >> log.txt

cc /home/pop/Daa/xyz.c

d = `time /home/pop/Daa/./a.out `

echo "dynamic" $d >> log.txt

But after executing the script the log.txt file contains only words recursion and dynamic. The time values seem to be missing. But executing time command on the commandline terminal gave the following output

real    0m0.001s
user    0m0.000s
sys 0m0.000s

How can get this output formatted to contain only the 'real' time of execution and written in the log file?

Upvotes: 2

Views: 2892

Answers (2)

Dennis Williamson
Dennis Williamson

Reputation: 359875

The output of time goes to stderr. You have to redirect it.

TIMEFORMAT=%R
r=$( { time /home/pop/Daa/./a.out; } 2>&1 )

And you can't have spaces around the equal sign. It is preferable to use $() instead of backticks since it's easier to read, there's no confusion with single quotes and it's easier to nest them.

Upvotes: 1

dogbane
dogbane

Reputation: 274532

When you assign values to a variable you shouldn't have spaces around the equals sign. For example:

r=`time /home/pop/Daa/./a.out`

If you only want the "real" time, use grep:

r=`time /home/pop/Daa/./a.out | grep real`

or use %e in the time command:

r=`time -f '%e' /home/pop/Daa/./a.out`

Upvotes: 1

Related Questions