قالب وردپرس درنا توس
Home / Tips and Tricks / How to Use the time Command on Linux

How to Use the time Command on Linux

  Linux PC with Terminal Window Open
Fatmawati Achmad Zaenuri / Shutterstock.com

Want to know how long a process is running and much more? The command Linux time returns the time statistics and gives you an insight into the resources used by your programs.

time Has Many Relatives

There are many Linux distributions and various Unix-like operating systems. Each of these has a standard command shell. The most common default shell in modern Linux distributions is the bash shell. However, there are many others, such as the Z shell (zsh) and the Korn shell (ksh).

All of these shells contain their own time command either as a built-in command or as a reserved word. If you enter time in a terminal window, the shell executes its internal command instead of using the GNU binary time which is provided as part of your Linux distribution.

We would like to use the GNU version of time since it has more options and is more flexible.

Which version is running?

You can use the type to check which version is running. command. type specifies whether the shell will process your statement itself with its internal routines or forward it to the GNU binary.

In a terminal window, type the word type [1

9459010ein] a space and then the word time and press Enter.

  Enter time 

  Enter time in a bash terminal window

As we can see in the bash shell time is a reserved word. This means that by default Bash uses its internal routines time .

  type time 

  type time in a zsh terminal window

In the Z shell (zsh) time is a reserved word, so by default, the internal shell routines are used ,

  Enter Time 

  Enter Time in a Korn Shell Window

In the Korn Shell Time ] is a keyword. Instead of the GNU time command, an internal routine is used.

RELATED: What is ZSH and why should you use it instead of Bash?

Executing the GNU Time Command

If the shell on your Linux system has an internal routine time you must explicitly specify whether to use the GNU time time . binary. You must specify either:

  • the entire path to the binary file, for example: For example, / usr / bin / time . Run the command which time to find this path.
  • Use the command command time .
  • Use a backslash such as time .

  time command output in a terminal window

The command at what time gives us the path to the binary file.

We can test this with / usr / bin / time . as a command to start the GNU binary. It works. We receive a response from the command time which tells us that we did not specify any command-line parameters for processing.

The entry of command time also works, and we receive the same usage information for time . The command instructs the shell to ignore the next command to process it outside the shell.

The use of a character before the command name corresponds to the use of command before the command name.

The easiest way to ensure that you use the GNU binary is to use the backslash option.

   time [19659035] time and  time output in a terminal window "width =" 644 "height =" 225 "src =" /pagespeed_static/1.JiBnMqyl6S.gif "onload =" pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon (this); "onerror =" this.onerror = null; pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon (this); "/>   time  calls the  shell version  time.   time  uses the binary file  time  . 

Using the command time

Let's schedule some programs.We use two programs named loop1 and loop2 They were created from loop1.c and loop2.c They do not do anything useful except to demonstrate the effects of some sort of inefficiency of coding.

This is loop1.c a string is needed in the two nested loops, the length is prefixed outside d he determined both nested loops.

  #include "stdio.h"
#include "string.h"
#include "stdlib.h"

int main (int argc, char * argv [])
int i, j, len, count = 0;
char szString [] = "how-outsiders-like-outsiders-like-outsiders-like-outsiders-like-outsiders-like-outsiders";

// Get the length of the string once outside the loops
len = strlen (szString);

for (j = 0; j <500000; j ++) {

for (i = 0; i <len; i ++) {

if (szString [i] == & # 39; - & # 39;
count ++;

printf ("% d hyphens counted  n", count);

Exit (0);

} // end of main 

This is loop2.c. The length of the string is determined again and again for each cycle of the outer loop. This inefficiency should show up in the timings.

  #include "stdio.h"
#include "string.h"
#include "stdlib.h"

int main (int argc, char * argv [])
int i, j, count = 0;
char szString [] = "how-outsiders-like-outsiders-like-outsiders-like-outsiders-like-outsiders-like-outsiders";

for (j = 0; j <500000; j ++) {

// get length of string all
// Time at which the loops are triggered
for (i = 0; i <strlen (szString); i ++) {

if (szString [i] == & # 39; - & # 39;
count ++;

printf ("% d hyphens counted  n", count);

Exit (0);

} // end of main 

Let's start the program loop1 and use time to measure the power.

   time ./loop1[19659042<[19459040<timeresultsforloopinaterminalwindow"width="646"height="147"src="/pagespeed_static/1JiBnMqyl6Sgif"onload="pagespeedlazyLoadImagesloadIfVisibleAndMaybeBeacon(this);"onerror="thisonerror=null;pagespeedlazyLoadImagesloadIfVisibleAndMaybeBeacon(this);"/>

Now we do the same for loop2 .

   time ./loop2[19659042[19459042[timeOutputForloop2inaTerminalWindow"width="646"height="147"src="/pagespeed_static/1JiBnMqyl6Sgif"onload="pagespeedlazyLoadImagesloadIfVisibleAndMaybeBeacon(this);"onerror="thisonerror=null;pagespeedlazyLoadImagesloadIfVisibleAndMaybeBeacon(this);"/>

This gives us two sets of results, but they have a really ugly format. We can do something about it later, but let's pick some information from the results.

When programs are running, there are two modes of execution to toggle between. These are referred to as user mode and kernel mode .

In short, a user-mode process can not directly access hardware or reference storage outside its own allocation. In order to access such resources, the process must direct requests to the kernel. When the kernel approves the request, the process switches to kernel mode until the request is satisfied. The process is then switched back to user mode.

The results for loop1 show that loop1 spent 0.09 seconds in user mode. Either it has not spent any time in kernel mode, or the time in kernel mode is too low to register after it has been rounded down. The elapsed total time was 0.1 seconds. loop1 received on average 89% of the CPU time over the entire elapsed time.

Executing the inefficient loop2 program took three times longer. The elapsed total time is 0.3 seconds. The processing time in user mode is 0.29 seconds. Nothing registers for kernel mode. loop2 received an average of 96% of CPU time for its duration.

Formatting the Output

You can customize the output of time using a format string. The format string may include text and format specifiers. The list of format specifiers can be found on the man page for time . Each of the format specifiers represents information.

When the string is printed, the format specifiers are replaced with the actual values ​​that they represent. The format specifier for the CPU percentage is, for example, the letter P . To indicate that a format specifier is not just a regular letter at time add a percent sign, such as % P . Let's use it in an example.

The option -f (format string) is used to tell the time that it is a format string.

Our format string is Specify the "Program:" characters and the name of the program (and any command-line parameters you pass to the program). The format specifier % C stands for "Scheduled Command Name and Command Line Arguments". n moves the output to the next line.

There are a variety of format specifiers that are case-sensitive. Therefore, make sure you enter them correctly if you do so yourself.

Next, we will print the Total Time: characters followed by the total elapsed time for this run (represented by % E ).

With n we specify another new line. We then print the characters "User Mode (s)", followed by the value of the CPU time spent in User Mode, given by % U .

We use n to give another new line. This time we prepare for the kernel time value. We print the characters "kernel mode (s)" followed by the format specifier for the kernel mode CPU time of % S .

Finally we will print the characters. " n CPU: Enter a new line and title for this data value. The format specifier % P indicates the average percentage of CPU time used by the timed process.

The entire format string is enclosed in quotation marks. We could have inserted some t characters to place tabs in the output, if we had taken care of aligning the values.

   time -f "Program:% C  nTotal:% E  nCustomer Mode (s)% U  nKernel Mode (s)% S  nCPU:% P" ./loop1[19659042[19459044"OutputtingFormatStringforLoopinTerminalWindow"width="646"height="212"src="/pagespeed_static/1JiBnMqyl6Sgif"onload="pagespeedlazyLoadImagesloadIfVisibleAndMaybeBeacon(this);"onerror="thisonerror=null;pagespeedlazyLoadImagesloadIfVisibleAndMaybeBeacon(this);"/>

Send output to A-file

To record the timings of the tests you have performed, you can send the output of -time to a file using the Option -o (output) .The output of your program will still be displayed in the terminal window, it is only the output of time which will be redirected to the file.

We can do the test rerun and save the output as follows in the file test_results.txt :

   time -o test_results.txt -f "Program:% C  nTotal:% E  nUser Mode (s)% U  nKernel Mode (s)% S  nCPU:% P" ./loop1
 cat test_results.txt 

 Output of format string for loop1 as a pipe in a file in a terminal window

The program output loop1 is displayed in the terminal window and the results go from time To the file test_results.txt .

If you want to capture the next set of results in the same file, you must use the characters -a . Option (Append) as follows:

   time -o test_results.txt -a -f "Program:% C  nTime:% E  nUser Mode (s)% U  nKernel Mode (s)% S  nCPU: % P "./loop2[19659034<cattest_resultstxt

 Output of loop2 format string appended in a terminal window

It should now be apparent why we used the format specifier % C used to include the name of the program in the output of the format string.

And We Have No More Time

The command time is probably most useful for programmers and developers to optimize the code Hood every time you launch a program.

Source link