Overview
The time command measures the execution time of a specific program or script and provides detailed resource usage statistics such as user CPU time, system CPU time, and real elapsed time. This helps in identifying performance bottlenecks in applications.
Key Measurement Metrics
- Real time: The actual elapsed time from when the command starts until it finishes.
- User CPU time: The time the CPU spent executing the command in user mode.
- System CPU time: The time the CPU spent executing the command in kernel mode.
Key Options
The time command can control output formats or request additional information through various options.
Output Format and Control
Generated command:
Try combining the commands.
Description:
`time` Executes the command.
Combine the above options to virtually execute commands with AI.
Usage Examples
Basic Usage
time ls
Measures the execution time of the ls command.
Output in POSIX Format
time -p sleep 1
Outputs the execution time of the sleep command in POSIX-compliant format.
Save Measurement Results to a File
time -o time_output.txt -a ls -l
Saves the measurement results of the ls -l command to the time_output.txt file. Since time's output goes to standard error, use 2>.
Output in Custom Format
time -f "Real: %e User: %U System: %S" sleep 1.5
Outputs real time, user CPU time, and system CPU time in a specific format.
Tips & Precautions
Points to note and additional tips when using the time command.
Shell Built-in time vs. External time Command
Shells like bash or zsh have their own built-in time commands. These typically output only real, user, and sys values and have more limited functionality than the external time command (/usr/bin/time). For more detailed information, you should explicitly call the external time command.
Explicitly Using the External time Command
\time sleep 1
/usr/bin/time sleep 1
To use the external time command instead of the shell's built-in time, prefix it with a backslash (\time) or specify its full path.
Measurement Accuracy
- Very short commands (in milliseconds) may have significant measurement errors.
- Measurement results can vary depending on the system's current load. For accurate measurements, it is recommended to repeat the command multiple times and check the average value.
Output Redirection
The output of the time command is sent to standard error (stderr). Therefore, to redirect the time measurement results to a file, you must use 2> or 2>>. For example, `time ls 2> time_result.txt` will display the output of ls on the screen and save only the time results to the file.