views:

333

answers:

3

Is is possible to print the execution time of a shell command with following combination?

root@hostname:~# "command to execute" && echo "execution time"
+4  A: 
root@hostname:~# time [command]

It also distinguishes between real time used and system time used.

Jason
That is certainly the basic answer - but there are some complications if you want to see the error output from the command and yet send the timing information to standard output as the question does. The time command writes to stderr. What you suggest is probably accurate enough - hence my +1.
Jonathan Leffler
+3  A: 

time is a built-in command in most shells that writes execution time information to the tty.

You could also try something like

start_time=`date +%s`
<command-to-execute>
end_time=`date +%s`
echo execution time was `expr $end_time - $start_time` s.

Or in bash:

start_time=`date +%s`
<command-to-execute> && echo run time is $(expr `date +%s` - $start_time) s
mobrule
+2  A: 

Don't forget that there is a difference between bash's builtin time (which should be called by default when you do time command) and /usr/bin/time (which should require you to call it by its full path).

The builtin time always prints to stderr, but /usr/bin/time will allow you to send time's output to a specific file, so you do not interfere with the executed command's stderr stream. Also, /usr/bin/time's format is configurable on the command line or by the environment variable TIME, whereas bash's builtin time format is only configured by the TIMEFORMAT environment variable.

$ time factor 1234567889234567891 # builtin
1234567889234567891: 142662263 8653780357

real    0m3.194s
user    0m1.596s
sys 0m0.004s
$ /usr/bin/time factor 1234567889234567891
1234567889234567891: 142662263 8653780357
1.54user 0.00system 0:02.69elapsed 57%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (0major+215minor)pagefaults 0swaps
$ /usr/bin/time -o timed factor 1234567889234567891 # log to file `timed`
1234567889234567891: 142662263 8653780357
$ cat timed
1.56user 0.02system 0:02.49elapsed 63%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (0major+217minor)pagefaults 0swaps
Mark Rushakoff
From `man bash`: "The TIMEFORMAT variable may be set to a format string that specifies how the timing information should be displayed"
Dennis Williamson
Oops - I *thought* there was some way to format it, but I missed it in `help time` because I only glanced over it and I thought it was a command line argument. I'll update the answer.
Mark Rushakoff