Understanding the Linux Time Command: Essential Skills for Performance Tuning!

Original link: https://bbs.huaweicloud.com/blogs/355148

Sometimes you may want to analyze your program based on the following parameters:
  • Time spent by the program in user mode
  • Time spent by the program in kernel mode
  • Average memory usage of the program
  • ETC

On Linux, we have a utility called time designed specifically for this purpose. The time utility takes the program name as input and displays information about the resources used by the program. Additionally, if the command exits with a non-zero status, this utility will display a warning message and the exit status.

The syntax of time is:
/usr/bin/time [options] program [arguments]
In the above syntax, ‘options’ refers to a set of optional flags/values that can be passed to the time utility to set or unset specific features. Here are the available options for the time command:
    • -v, –verbose: Pass this option when a detailed description of the output is needed.
    • –quiet: This option prevents the time utility from reporting the program’s status.
    • -f, –format: This option allows the user to control the output format of the time utility.
    • -p, –portability: This option sets the output format to conform to POSIX.
real %e
user %U
sys %S
  • -o FILE, –output=FILE: This option allows the user to redirect the output of the time utility to a file. This option allows the time utility to overwrite the file FILE.
  • -a, –append: This option allows the time utility to append information to the file FILE instead of overwriting it.
When running the time command, the types of output it provides are as follows:
# /usr/bin/time ls
anaconda-ks.cfg  bin  install.log  install.log.syslog  mbox
0.00user 0.00system 0:00.00elapsed 0%CPU (0avgtext+0avgdata 3888maxresident)k
0inputs+0outputs (0major+304minor)pagefaults 0swaps
As we can see above, in addition to executing the command, the last two lines of output are the resource information output by the time command.
Note: In the example above, the time command is run without any options. So this is the default output generated by the time command, which is not formatted correctly.
From the output, we can see that the default format of the generated output is:
%Uuser %Ssystem %Eelapsed %PCPU (%Xtext+%Ddata %Mmax)k
%Iinputs+%Ooutputs (%Fmajor+%Rminor)pagefaults %Wswaps

Format Options

This option allows users to decide the output generated by the time command. In the previous section, we discussed the default format used in the output. In this section, we will learn how to specify a custom format.
The format string typically consists of ‘resource specifiers’ scattered among plain text. A percent sign (`%’) in the format string causes the following character to be interpreted as a resource specifier.
A backslash (`\’) introduces ‘backslash escaping’, converting it to a single printable character in the output. `\t’ outputs a tab, `\n’ outputs a newline, `\\’ outputs a backslash. A backslash followed by any other character outputs a question mark (`?’) followed by a backslash, indicating an invalid backslash escape was given.
Other text in the format string is copied verbatim to the output. The time command always prints a newline after printing resource usage information, so the format string usually does not end with a newline (or `0`).
For example:
$ /usr/bin/time -f "\t%U user,\t%S system,\t%x status" date
Sun Jan 22 17:46:58 IST 2012
	0.00 user,	0.00 system,	0 status
So we see in the example above that we are trying to change the output format by using a different output format.

Resources

Since we discussed that the time utility displays information about the program’s resource usage, in this section, we list the resources that this utility can track and their corresponding specifiers.
From the man page:
  • C – The name and command line parameters of the command being timed.
  • D – The average size of the process’s non-shared data area, in kilobytes.
  • E – The actual (clock) time used by the process, in [hours:] minutes: seconds.
  • F – The number of major or I/O-required page faults that occurred while the process was running. These are faults where pages actually migrate out of main memory.
  • I – The number of file system inputs for the process.
  • K – The average total (data + stack + text) memory usage of the process, in kilobytes.
  • M – The maximum resident set size of the process during its lifetime, in kilobytes.
  • O – The number of file system outputs for the process.
  • P – The percentage of CPU the job received. This is just user + system time divided by total runtime. It also prints a percent sign.
  • R – The number of minor or recoverable page faults. These pages are invalid (thus they fault) but have not yet been claimed by other virtual pages. Thus the data in the pages is still valid but must update the system table.
  • S – The total number of CPU seconds used by the process (in kernel mode), in seconds.
  • U – The number of CPU seconds directly used by the process (in user mode), in seconds.
  • W – The number of times the process was swapped out of main memory.
  • X – The average amount of shared text in the process, in kilobytes.
  • Z – The page size of the system, in bytes. This is a constant for each system but varies by system.
  • c – The number of involuntary context switches of the process (because the time slice expired).
  • e – The actual (clock) time used by the process, in seconds.
  • k – The number of signals sent to the process.
  • p – The average non-shared stack size of the process, in kilobytes.
  • r – The number of socket messages received by the process.
  • s – The number of socket messages sent by the process.
  • t – The average resident set size of the process, in kilobytes.
  • w – The number of times the program voluntarily switched context, such as when waiting for I/O operations to complete.
  • x – The exit status of the command.
So we can see there is a long list of resources that can be tracked for their usage by the time utility.

Why /usr/bin/time? (And Not Just Time)

Let’s not use /usr/bin/time but rather time.
$ time -f "\t%U user,\t%S system,\t%x status" date
-f: command not found 

real	0m0.255s
user	0m0.230s
sys	0m0.030s
From the output above, it can be seen that using the time command without the full path (/usr/bin/time) produces an error regarding the ‘-f’ flag. Additionally, the format of the output is neither the format specified in the command nor the default format we discussed earlier. This leads to confusion about how this output was generated.
If the time command is executed without the full path (/usr/bin/time), it executes the built-in time command of the bash shell.
  • Use ‘man time’ to view the man page for /usr/bin/time
  • Use ‘help time’ to view information on the built-in bash time.



Previous Recommendations



Online Linux CPU 100% Fault Diagnosis Summary
19 Common Issues with K8s Clusters, Recommended to Save
Developers Use Redis Like This, I Ended Up Taking the Blame!
11 Jenkins Usage Tips, Over 90% Haven't Used Them!
Nginx Working Principles and Optimization Summary (Super Detailed)
Redis Cluster Solutions: Master-Slave, Sentinel, and Cluster
Six High-Frequency Linux Operation and Maintenance Troubleshooting Notes!
17 Common Operation and Maintenance Metrics, 90% People Don’t Know!
Why Does Performance Drop So Much After Containerizing Applications?
How to Handle MySQL Process CPU Spiking to 900%?
Nginx Rate Limiting Explained, Responding to Traffic Surges and Malicious Attacks
Linux Disk Overloaded, How to Troubleshoot?
The Most Comprehensive Guide to CentOS System Security Configuration!
25 Common MySQL Interview Questions and Answers
When the Interviewer Asks You: How to Handle CPU Spiking to 900%?
With This Article on Nginx Performance Optimization, You’re Good to Go!
Which JDK Should Be Used on K8s? 8 Types of JDK Performance Testing
11 Performance Analysis Tools for Linux, Fast and Accurate!
Nginx Log Rotation Tool
Ali Nacos Learning Manual, Very Detailed!
K8s Pod “OOM Killer”, Found the Reason
17 Common Operation and Maintenance Metrics, Frequently Asked in Interviews!
K8s Pod Troubleshooting, A Little-Known Technique!
Summary of High Concurrency Performance Optimization Notes for Major Factories on Nginx
Nginx+Lua+Redis Implementing Gray Release Systems
Building a CI/CD System Based on Jenkins
Seven Major Application Scenarios of Nginx (with Configuration)
CI/CD Practice Summary of Zhu Bajie Network
16 Diagrams Hard-Core Explanation of Kubernetes Networking
Practical Implementation of Full-Stack DevOps Observability Platform for Dewu App
The Learning Manual for Nginx (Recommended to Save!)
9 Practical Shell Scripts, Recommended to Save!
Essential Kubectl Commands for K8s Operations
The Most Comprehensive Explanation of Jenkins Pipeline
40 Common Interview Questions for Nginx
Common Linux Operation and Maintenance Interview Questions, Must-See for Job Seekers!
50 Common Interview Questions for Linux Operation and Maintenance Engineers




Light it up, the server won’t go down for three yearsUnderstanding the Linux Time Command: Essential Skills for Performance Tuning!

Leave a Comment