What is the time command in Linux for?

time command in Unix is used to find the time taken by a particular command to execute. This is very useful when we want to time a particular command or a particular script to know the amount of time it consumes. Not only the elapsed time, the time command also tells the amount of time spent in the user and kernel spaces as well.

$ time

real 0m0.000s
user 0m0.000s
sys 0m0.000s

time command output shows 3 different components:
real - The total time elapsed during the command which includes the time taken for the process.
user - The time taken for the process only in the user space. This does not include kernel calls.
sys - The time taken for the process in system space (for kernel related calls )

1. Using time for a command:

$ time ls
f1.c f2.c

real 0m0.01s
user 0m0.00s
sys 0m0.01s

This indicates the ls command has taken a total of 0.01 second to finish, which is the time elapsed.

2. Using time command for a simple script:
Let us write a script, try.sh, which prints a welcome message:

$ cat try.sh
#!/bin/bash

echo "welcome"

Running the time command:

$ time ./try.sh
welcome

real 0m0.03s
user 0m0.01s
sys 0m0.02s

This script has taken a total of 0.03 seconds to execute.

3. Timing the sleep in the script:
sleep command's duration do not go against user or sys, it is always against the real output.

$ cat try.sh
#!/bin/bash

sleep 3
echo "welcome"

Running the time command:

$ time ./try.sh
welcome

real 0m3.04s
user 0m0.03s
sys 0m0.01s

As seen above, the sleep duration goes entirely in the real, not in the user or sys.
Capturing time output:
time command output is re-directed to standard error terminal, and not standard output like other Unix commands. Hence, time command output cannot be re-directed to a file in a normal way.

1. To retrieve only the real time of the time output:

$ time ./try.sh | grep real
welcome

real 0m1.05s
user 0m0.02s
sys 0m0.04s

As seen, grep does not help since the time command output is not in the STDOUT.

$ (time ./try.sh) 2>&1 | grep real
real 0m1.05s

By re-directing the standard error to standard output, the time command output can now be passed as standard input to other commands.

2. To re-direct the time command output to a file:

$ (time ls ) 2>file