Loop without a delay

Hi,

I am trying to understand what would happen if ther is a loop without any delay like sleep statement, I feel that would add a lot of load onto the CPU. Trying to understand how the load is reduced by the introduction of sleep().

Thanks and regards
Zulfi

The kernel gives resources to a process. When other processes want the cpu resource, the looping process loses the cpu - this is called a context switch.

Simply having a forever loop is a waste of resources. Period. If you want to have a process hanging around waiting for some work to do, then there are other better ways. For example, use signals.

If you give us a concrete shell script example we can help clear up your confusion.

Thanks for the reply,

 
 
filefound=0
 
while [[ $filefound -eq 0 ]]
do
 
if [[ -f abc.dat ]]
then
mv abc.dat xyz.dat
filefound=1
fi
 
done

In the above if the file is not found the loop keeps iterating, adding a sleep command will introduce some wait between iterations. Just wondering if by adding the sleep will add any advantage in terms reducing processor load OR it just doesn't make any difference.

Thanks
Zulfi

Adding a sleep will reduce the overall load on a processor. Even a one second sleep is good enough. The process arranges for a signal to be delivered one second in the future. Then it will call pause() and do nothing until the signal arrives. A second is a long time to a modern cpu. In a small loop like you show the script will run for a few milliseconds then do nothing at all for a full second. So most of the time, this script is doing nothing.