Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print execution time of a shell command

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

root@hostname:~# "command to execute" && echo "execution time" 
like image 975
jack Avatar asked Nov 01 '09 04:11

jack


People also ask

How do I print the current time in shell?

Sample shell script to display the current date and time #!/bin/bash now="$(date)" printf "Current date and time %s\n" "$now" now="$(date +'%d/%m/%Y')" printf "Current date in dd/mm/yyyy format %s\n" "$now" echo "Starting backup at $now, please wait..." # command to backup scripts goes here # ...

How do I execute a shell script execution time?

You can use ' time ' command to get the execution time of the script. This command will call the Tcl interpreter count times to evaluate script (or once if count is not specified).


2 Answers

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 
like image 153
mob Avatar answered Sep 20 '22 06:09

mob


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 
like image 34
Mark Rushakoff Avatar answered Sep 23 '22 06:09

Mark Rushakoff