views:

84

answers:

4

I'd like to use the time command in a bash script to calculate the elapsed time of the script and write that to a log file. I only need the real time, not the user and sys. Also need it in a decent format. e.g 00:00:00:00 (not like the standard output). I appreciate any advice.

A: 
Archimedix
Seems incorrect: Time in seconds: 46 (OK), Pretty format: 00:00:00:46 (incorrect). Using time command: real 0m46.018s user 0m7.630s sys 0m1.190s
Robertico
Hm, I'm not quite sure what 00:00:00:00 is supposed to mean – I was guessing it meant [days]:[hours]:[minutes]:[seconds] ? That is what it shows, but you are free to adjust the code to calculate what you need.
Archimedix
excuses for the typo.Supposed to be 00:00:00.0000 (milliseconds)[hours]:[minutes]:[seconds].[milliseconds]
Robertico
A: 

Not quite sure what you are asking, have you tried:

time yourscript | tail -n1 >log

Edit: ok, so you know how to get the times out and you just want to change the format. It would help if you described what format you want, but here are some things to try:

time -p script

This changes the output to one time per line in seconds with decimals. You only want the real time, not the other two so to get the number of seconds use:

time -p script | tail -n 3 | head -n 1
Amoss
I want to include it in my script.
Robertico
Yes, if that was unambiguous then I wouldn't pointed out that it needs clarification. Why not use two scripts, one that calls the other?
Amoss
Because i've already 3 scripts. I saw an example like this: { time { # section code goes here} } 2> timing.logBut i only need the real time, not the user and sys. Also need it in a decent format. e.g 00:00:00:00 (not like the standard output).
Robertico
ok, so you already know how to time a section, so that was just unnecessary confusion in your question. Is what you really want to know how to turn the time output into something easier to process, like just the number of seconds?
Amoss
yes i'd like to know how to turn the time output into something easier to process.
Robertico
+2  A: 

From the man page for time: 1)There may be a shell built-in called time, avoid this by specifying /usr/bin/time 2)You can provide a format string and one of the format options is elapsed time - %E

/usr/bin/time -f'%E' $CMD

Example:

/usr/bin/time -f'%E' ls /tmp/mako/
res.py  res.pyc
0:00.01
Martin Thomas
That's why the command: time -f'%E' was not working, but /usr/bin/time -f'%E' works fine. Thx
Robertico
Do you want to accept this as the answer?
Martin Thomas
A: 

To use the Bash builtin time rather than /bin/time you can set this variable:

TIMEFORMAT='%3R'

which will output the real time that looks like this:

5.009

or

65.233

The number specifies the precision and can range from 0 to 3 (the default).

You can use:

TIMEFORMAT='%3lR'

to get output that looks like:

3m10.022s

The l (ell) gives a long format.

Dennis Williamson