How to Time a How Long a Terminal Command Takes
It is no doubt that time is the most important resource we have. As a sys admin, you will constantly monitor your script and command time usage more times not.
Especially when configuring multiple devices, determining how long a script or command takes to complete can allow you to determine when is the right to perform maintenance, etc.
In this post, you will understand the tools provided by the Linux system to calculate the time it takes for a script or command to complete execution.
Get your cup of coffee ready and let’s jump in.
Linux time
Command
The time
command in Linux and other Unix systems provides us with the ability to monitor how long a command takes.
The time
command is built-in all major shells and available in almost all Linux devices. The command follows a syntax as shown below:
time [-al] [-h | -p] [-o file] utility [argument ...]
The command accepts the following options:
-a If the -o flag is used, append to the specified file rather than overwriting it.
Otherwise, this option has no effect.
-h Print times in a human friendly format. Times are printed in minutes, hours, etc. as
appropriate.
-l The contents of the rusage structure are printed as well.
-o file
Write the output to file instead of stderr. If file exists and the -a flag is not
specified, the file will be overwritten.
-p Makes time output POSIX.2 compliant (each time is printed on its own line).
Example 1 - time
command without parameters
If we run the time
command without any arguments, the command will time details when the command run. These includes statistics such as the elapsed real time between invocation and termination, elaspsed user CPU time, system CPU time, etc.
Example:
time
Output:
shell 0.02s user 0.05s system 0% cpu 6:18.79 total
children 0.61s user 0.32s system 0% cpu 6:18.79 total
Example 2 - Time the ls
Command
The example below shows how to use the time
command to determine how long it takes to list files and directories in the /var/log
directory.
time ls -la /var/log
The command should show the file listing followed by the elapsed duration stats. A sample output is as shown:
ls -la /var/log 0.00s user 0.01s system 65% cpu 0.019 total
Keep in mind that the elapsed time is calculated in CPU seconds and not human seconds.
NOTE: You may get different results and command options if you using the time
command provided by your built-in shell or the GNU time command.
Conclusion
In this tutorial, we explored how to time how long a command or a script takes to finish execution using the time
command. You can check the man pages with the command man time
to discover further.
Leave us a comment down below, share and see you in the next one!!