Unix / Linux: Time a Command

Objective: Track the amount of time a command takes on Unix / Linux.

The time command can be used to track the amount of time taken for a command to run.

$ time /path/to/command
real    0m2.005s
user    0m0.000s
sys     0m0.000s

The above output indicates that the command took slightly more than 2 seconds to execute. The real time is the elapsed “wall clock” time. It is like using a stop watch to monitor the process start and stop time.

There are 2 variants of the time command. The first is the standalone external time command normally installed in /usr/bin. The other is a shell keyword or builtin command. To check if you are using the shell keyword / builtin or the external time binary, use the type command.

$ type time
time is a shell keyword

The about output means that the time command is a shell keyword, and the command will be executed by the shell. So, by default, the shell will not execute the external time command found in /usr/bin. On some shells, type command (eg. tcsh) will not work. Use which command instead on such shells.

$ which time
time: shell built-in command.

To force the shell to use the external time command, use one of the two syntaxes below. Not all shells will support both syntaxes.

$ command time /path/to/command
$ \time /path/to/command

To get the elapsed real (wall clock) time used by a process in seconds, use the following syntax.

$ \time -f "%e" sleep 2

The above output shows that the “sleep 2” command took 2 seconds to execute, which is correct based on the argument “2” that was passed to the sleep command.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }