开发者

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/po开发者_开发百科p/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?


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.


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`
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜