time, timeout, sleep & usleep

These 4 commands are all time related but they perform completely different tasks. 

The time command gives us very simple execution timings for a script or command:

root:~> time /etc/cron.daily/mlocate
real     0m0.100s
user     0m0.056s
sys      0m0.044s

The real figure shows the elapsed real time between invocation and termination. This is the actual time that it took to execute the task at hand but it can be very misleading when the system is heavily loaded or the process has a low execution priority. In other words, the process might spend a considerable amount of time waiting for CPU resources but actually need very little CPU time to complete.

We can spot extraneous reasons for a slow execution by comparing the real figure with the sum of user + sys . The user and sys numbers show the user and kernel CPU time consumed.

The timeout command is very useful when a script/command should execute within a certain amount of time but it might block/hang for some reason. Let’s say that a script called pingserv4.sh should execute within 3 seconds in normal circumstances. Sometimes though it hangs and it needs to be manually killed every time. If we want to avoid that we can execute:

root:~> timeout 6 ./pingserv4.sh

In the example above we are giving 6 seconds to pingserv4.sh to complete before it is sent a SIGTERM signal. We can send it any other signal (e.g. SIGKILL) and set the timeout to any number of seconds, minutes, hours or days…

root:~> timeout 5s ./pingserv4.sh -­k 5
root:~> timeout 1h ./pingserv4.sh ­-s SIGKILL

In the 1st example pingserv4.sh is given 5 seconds to complete before a SIGTERM signal is sent. If after 5 more seconds it is still running, a SIGKILL signal will be sent.

In the 2nd example pingserv4.sh is given 1 hour to complete before a SIGKILL signal is sent.

Sometimes, especially within scripts, we need to wait a certain amount of time for some task to complete or some condition to be checked. When that is the case we can use sleep. The sleep command switches the process to an idle state for a certain number of seconds/minutes/hours/days before awaking and continuing execution.

root:~> sleep 5      → process sleeps for 5 seconds
root:~> sleep 1s     → process sleeps for 1 second
root:~> sleep 1m     → process sleeps for 1 minute
root:~> sleep 1h     → process sleeps for 1 hour
root:~> sleep 1d     → process sleeps for 1 day

If the interval we need to wait is far less than a second (let’s say centiseconds or milliseconds) then we can use usleep which counts the intervals in microseconds (1 millionth of a second).

root:~> usleep 10000     → sleeps 10,000 microseconds or 10 milliseconds or 1 centisecond

<< stty, tty, clear & reset                   watch >>