When working in a Linux terminal, you often encounter situations where you need to monitor the execution time of a command or limit its runtime. The time
and timeout
commands are powerful tools that can help you achieve these tasks. In this tutorial, we’ll explore how to use both commands effectively, along with practical examples.
Using the time
Command
The time
command in Linux is used to measure the execution time of a specified command or process. It provides information about the real, user, and system time used by the command. The real time represents the actual elapsed time, while the user time accounts for the CPU time consumed by the command, and the system time indicates the time spent by the system executing on behalf of the command.
Syntax
time [options] command
Example
Let’s say you want to measure the time taken to execute the ls
command:
time ls
The output will provide information like:
real 0m0.005s user 0m0.001s sys 0m0.003s
In this example, the real
time is the actual time taken for the command to execute, while user
and sys
times indicate CPU time spent in user and system mode, respectively.
Using the timeout
Command
The timeout
command allows you to run a command with a specified time limit. If the command does not complete within the specified time, timeout
will terminate it. This can be especially useful when dealing with commands that might hang or run indefinitely.
Syntax
timeout [options] duration command
Example
Suppose you want to limit the execution of a potentially time-consuming command, such as a backup script, to 1 minute:
timeout 1m ./backup_script.sh
If backup_script.sh
completes within 1 minute, the command will finish naturally. However, if it exceeds the time limit, timeout
will terminate it.
By default, timeout
sends the SIGTERM signal to the command when the time limit is reached. You can also specify which signal to send using the -s (–signal) option.
Combining time
and timeout
You can also combine the time
and timeout
commands to measure the execution time of a command within a time-constrained environment.
timeout 10s time ./long_running_command.sh
In this example, the timeout
command ensures that the time
command (which measures execution time) doesn’t run indefinitely. The execution will terminate after 10 seconds, and the time
output will provide insights into the resources used during that time.
Conclusion
The time
and timeout
commands are valuable tools for managing command execution time in Linux. The time
command helps you understand the resource utilization of a command, while the timeout
command lets you control the execution time of commands to prevent them from running indefinitely. By mastering these commands, you can better manage your terminal tasks and improve your overall efficiency as a Linux user.