A Brief Story of Time and Timeout
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
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.
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.
time [options] command
Let's say you want to measure the time taken to execute the
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
sys times indicate CPU time spent in user and system mode, respectively.
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.
timeout [options] duration command
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
backup_script.sh completes within 1 minute, the command will finish naturally. However, if it exceeds the time limit,
timeout will terminate it.
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.
You can also combine the
timeout commands to measure the execution time of a command within a time-constrained environment.