Use Time Command in Linux

Use Time Command in Linux measures the duration a command takes to execute. It shows real time elapsed, user CPU time, and system CPU time, helping developers analyze performance and optimize scripts efficiently in a Linux environment.

🤖AI Overview:

Use Time Command in Linux to measure how long a specific command or process takes to execute. It provides information on real time, user CPU time, and system CPU time, helping evaluate the performance and resource usage of commands or scripts. This command is useful for comparing execution durations and system resource consumption in Linux environments.

Prerequisites to Use Time Command in Linux

To let this tutorial works better, consider the below options and continue reading.

A system or Linux VPS hosting running any distribution.

A non-root user with sudo privileges.

What is Time Command?

In Linux and Unix-like operating systems, you can find out how long a particular operation will take to execute by using the time command. Typically, it’s employed to gauge how well scripts or instructions function. A command performs better the quicker it completes its task. The Time command is a useful tool for evaluating a command’s effectiveness because it can also show how much of the system resources the process is using.
If you want to choose between two cron jobs that can execute the same operation, for instance. Running the time command will show you how long it will take for each cron job to finish its tasks. Remember that it varies based on the shell you use.

Different versions of the Time Command

Let’s see the different versions of the time command in the Linux system. Bash, Zsh, and GNU Default Linux (GNU) are the three versions of the Time Command.

Use the command below to check which Linux time command version applies to your system:

$ type time

The output of:

time is a shell keyword” means that you are using the Bash time command.

The output of:

time is a reserved word” means that you are using the Zsh time command.

The output of:

time is usr/bin/time” means that you are using the GNU time command.

Tutorial Use Time Command in Linux

Knowing Linux Commands will help you execute tasks more efficiently. Stay with us to learn the Time command as one of the Linux commands. In this article, we will use examples to show you how to use the time command.

Firstly, let’s see the syntax of the Linux time command. Then, you will learn how to read its output. So, open your shell program and type:

$ time command
$ time command arg1 arg2 ... argN
$ time [options] command arg1 arg2 ... argN

Time runs the specified command with any supplied arguments (arg). Time produces information once a command completes its operation, including how long it took to run and what resources it consumed. Time will output a warning message and the exit status if the program command fails and exits with a non-zero status.

You can choose the data to display in the system resource use section by inputting the string format that the command uses. The value of the time environment variable will be utilized as the format if the user does not provide a format, but it is set. If not, the time’s built-in default format will be applied.

Tip: After the command, anything supplied will be viewed as an argument.

Examples of Linux Time Command

In this section, we will review how to use the time command in Linux and also the way you can read its output by learning the syntax of the Linux time command. Here, you will see how easy is to use the time command. You just need to open your sell program and type the related command.

Generally, you can run the following command to view all the options which are possible to be used for time:

$ man time

Depending on your operating system and your running version, the above command gives you a list of options you can use to change the Linux time command.

Also, to verify the location, run the command below:

$ type -a time
$ command -V time

The output should be like as below:

time is a shell keyword
time is /usr/bin/time
time is /bin/time

The example below displays the time taken to complete the process of moving a file to a different directory. To find out how long will it take, run:

$ time mv example.txt example-dir

As you will see in the output, the example.txt file has been moved to example-dir.

Enter the following to calculate how long it takes to execute the date program:

$ time date

Then, give a full path to time binary to use the external time command:

$ /usr/bin/time -p date

How to read the output of the Linux Time Command?

Understanding the Output of the Linux time command helps you to know the advantages of this command. Here, we explain how to read the output.

  • Real-time (real): the actual amount of time needed for the procedure to be complete from beginning to end. This includes any time consumed by additional procedures as well as any time needed to wait for them to finish.
  • User time (user): the length of time the process took the CPU in user mode. Blocks of time and other processes are not included.
  • System time (sys): the total amount of time the process used the CPU in kernel mode. Other processes, as well as time spent being blocked by other processes, are not counted, just like user time.

Let’s continue reviewing examples to learn to use Time Command in Linux perfectly. To download the VirtualBox installer, use the command below, and install this open-source virtual machine program.

$ time wget https://download.virtualbox.org/virtualbox/6.1.28/virtualbox-6.1_6.1.28-147628~Ubuntu~eoan_amd64.deb

You will see three figures after the download is finished: real, user, and sys. As you can see, they display the amount of time that has passed throughout the download in minutes and seconds in real, user, and system modes.

Redirect time command output to a file

To save a record of the time command information (in the output.time.txt file), the syntax would be like this:

time date 2> output.time.txt
/usr/bin/time -p date 2> output.time.txt

If you are GNU/Linux user, you can use the following commands to write the resource use statistics to file instead of to the standard error stream:

$ /usr/bin/time -o output.time.txt -p date
$ cat output.time.txt

If you want the resource consumption data to be appended to the output file rather than overwritten, pass the -a option. Only the -o option and this option are useful together:

$ /usr/bin/time -a -o output.time.txt -p sleep 2
$ cat output.time.txt

Also, you can run the command below to control the time command output format:

$ /usr/bin/time -f 'FORMAT' -p command

How to write the Output to a File correctly?

You might occasionally want to save the information you received using time. So, you can write the command output to a file using the format option. The GNU time command’s -o option allows you to generate a new output file containing data from the other command, which is exactly what you want to do.

To do this, use the command below to save the ping information of yourdomain.com. It will also save the details of its process into a new file.

$ time -o yourdomain-ping-info.log ping yourdomain.com

Bash shell users must call up the external time command if they want to use -o or any other option. To do this, explicit path usr/bin/time must be used instead of just time.

$ usr/bin/time -o yourdomain-ping-info.log ping yourdomain.com

Also, the syntax of using bash’s builtin time command in Linux / Unix is as below:

$ time command
$ time ls
$ TIMEFORMAT="%P" time ls
$ TIMEFORMAT="%U" time sleep 3
$ TIMEFORMAT="%S" time sleep 3
$ TIMEFORMAT="%R" time sleep 2

Next, you can use the following command to check the content of yourdomain-ping-info.log.

$ cat yourdomain-ping-info.log

As we mentioned, it is possible to get detailed output in a File. There’s a chance that the default time command output won’t provide you with all the information you need to understand a certain process. Add the -v option to the time command in Linux to display detailed output.

Run the following command to find the ping or response time of yourdomain.com. In this way, detailed information about the process will be displayed.

$ time -v ping yourdomain.com

But you can use the external time command by entering the full path usr/bin/time, if you do not use the GNU time command.

$ usr/bin/time -v ping yourdomain.com

As an alternative, users can use the following output format parameters to specify the details they want to be displayed in the output when entering the time command:

Formatting the output of /usr/bin/time:

FORMATDESCRIPTION
% A literal `%’.
CName and command line arguments of the command being timed.
DAverage size of the process’s unshared data area, in Kilobytes.
EElapsed real (wall clock) time used by the process, in [hours:]minutes:seconds.
FNumber of major, or I/O-requiring, page faults that occurred while the process was running. These are faults where the page has actually migrated out of primary memory.
INumber of file system inputs by the process.
KAverage total (data+stack+text) memory use of the process, in Kilobytes.
MMaximum resident set size of the process during its lifetime, in Kilobytes.
ONumber of file system outputs by the process.
PPercentage of the CPU that this job got. This is just user + system times divided by the total running time. It also prints a percentage sign.
RNumber of minor, or recoverable, page faults. These are pages that are not valid (so they fault) but which have not yet been claimed by other virtual pages. Thus the data in the page is still valid but the system tables must be updated.
STotal number of CPU-seconds used by the system on behalf of the process (in kernel mode), in seconds.
UTotal number of CPU-seconds that the process used directly (in user mode), in seconds.
WNumber of times the process was swapped out of main memory.
XAverage amount of shared text in the process, in Kilobytes.
ZSystem’s page size, in bytes. This is a per-system constant, but varies between systems.
cNumber of times the process was context-switched involuntarily (because the time slice expired).
eElapsed real (wall clock) time used by the process, in seconds.
kNumber of signals delivered to the process.
pAverage unshared stack size of the process, in Kilobytes.
rNumber of socket messages received by the process.
sNumber of socket messages sent by the process.
tAverage resident set size of the process, in Kilobytes.
wNumber of times that the program was context-switched voluntarily, for instance while waiting for an I/O operation to complete.
xExit status of the command.

How to use time command on Linux or Unix with formatting

When you decide to show just the user, system, and total time using the format option, run:

$ /usr/bin/time -f "%E real,%U user,%S sys" sleep 2
$ /usr/bin/time -f "%E real,%U user,%S sys" /path/to/script

The output will be something like the below:

0:02.00 real,0.00 user,0.00 sys

The following command will display the percentage of CPU:

$/usr/bin/time -f "CPU Percentage: %P" command
$ /usr/bin/time -f "CPU Percentage: %P" grep vivek /etc/passwd
$ /usr/bin/time -f "CPU Percentage: %P" find /etc/ -type f -iname "a*.conf"

CPU Percentage: 76%

Conclusion

Effectively using the time command in Linux empowers developers to measure execution time and resource usage efficiently. Understanding and interpreting the real, user, and system times allow precise diagnosis of performance bottlenecks, while advanced options provide flexibility for automation and reporting.

Best practices include favoring the external time command for advanced features, customizing format output, redirecting logs for persistence, and integrating with other monitoring tools. Consistent usage of time in development and production environments can significantly aid in optimizing applications and troubleshooting performance issues.

FAQ

You use the syntax "time command [arguments]" to run the target command while simultaneously measuring and displaying its resource usage and execution time once completed.

Real time is the total elapsed time including waits, user time is the CPU time spent in user mode, and sys time is the CPU time spent in kernel mode for the process.

Use the "-o filename" option with the GNU time command to save metrics to a file or redirect standard error stream (2>) to capture output when using the shell built-in versions.

Yes. The main variants are Bash's built-in time, Zsh's reserved word version, and the GNU external time command located at /usr/bin/time, each with subtly different features.

The GNU time command supports the "-f" option enabling you to specify a custom format string to display preferred statistics such as CPU percentage, elapsed time, or memory usage.

Developers can measure script execution speed, compare performance of different commands or cron jobs, monitor resource consumption during builds, and optimize code efficiency.

CPU percentage indicates the portion of CPU capacity utilized by the command during its run. Values exceeding 100% may indicate multi-threading across multiple CPU cores.

Verify which version of time is executing using "type time", explicitly call the GNU time using its full path, and consult the manual page via "man time" for detailed option explanations.

Yes, the Time command measures total elapsed time and CPU usage regardless of IO or network operations, making it suitable for timing downloads, file transfers, and similar tasks.

Leave a Reply

Your email address will not be published. Required fields are marked.