[shell] 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"

This question is related to shell command-line

The answer is


root@hostname:~# time [command]

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


In zsh you can use

=time ...

In bash or zsh you can use

command time ...

These (by different mechanisms) force an external command to be used.


If I'm starting a long-running process like a copy or hash and I want to know later how long it took, I just do this:

$ date; sha1sum reallybigfile.txt; date

Which will result in the following output:

Tue Jun  2 21:16:03 PDT 2015
5089a8e475cc41b2672982f690e5221469390bc0  reallybigfile.txt
Tue Jun  2 21:33:54 PDT 2015

Granted, as implemented here it isn't very precise and doesn't calculate the elapsed time. But it's dirt simple and sometimes all you need.


Adding to @mob's answer:

Appending %N to date +%s gives us nanosecond accuracy:

start=`date +%s%N`;<command>;end=`date +%s%N`;echo `expr $end - $start`

For a line-by-line delta measurement, try gnonom.

It is a command line utility, a bit like moreutils's ts, to prepend timestamp information to the standard output of another command. Useful for long-running processes where you'd like a historical record of what's taking so long.

Piping anything to gnomon will prepend a timestamp to each line, indicating how long that line was the last line in the buffer--that is, how long it took the next line to appear. By default, gnomon will display the seconds elapsed between each line, but that is configurable.

gnomon demo


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

Just ps -o etime= -p "<your_process_pid>"