patterncCritical
Using a for-loop or sleeping to wait for short intervals of time
Viewed 0 times
waitshortlooptimeintervalssleepingforusing
Problem
I need to wait for short intervals of time in my program, but I really don't want to include
I do this when I don't really have a specific interval to set for sleep.
Is there anything wrong with this? Would this harm the program in any way?
In C I know that if I did include
unistd.h just to use sleep, so I'm doing it this way:int main()
{
for(int i=0; i<=100000000000; i++); // <----- note that the loop doesn't do anything
return 0;
}I do this when I don't really have a specific interval to set for sleep.
Is there anything wrong with this? Would this harm the program in any way?
In C I know that if I did include
unistd.h, and that if I used sleep(), that the following code would also make the program wait for a short interval of time:int main()
{
sleep(2); //or whatever the number (in seconds)
return 0;
}Solution
The biggest problem with using a for-loop to do this is that you are wasting CPU power.
When using
But in the for-loop the CPU continuously have to do work to increase a variable. For what purpose? Nothing. But the CPU doesn't know that. It's told to increase the variable, so that's what it will do. Meanwhile, other programs aren't given as much time to do their work because your program is taking up time.
Please don't waste CPU power, use the
As stated in a comment, additionally, the compiler may optimize out an empty loop, and the attempt to pause may be lost. So either you will waste CPU power, or you will not pause at all.
When using
sleep, the CPU can, in a sense, take a break (hence the name "sleep") from executing your program. This means that the CPU will be able to run other programs that have meaningful work to do while your program waits.But in the for-loop the CPU continuously have to do work to increase a variable. For what purpose? Nothing. But the CPU doesn't know that. It's told to increase the variable, so that's what it will do. Meanwhile, other programs aren't given as much time to do their work because your program is taking up time.
Please don't waste CPU power, use the
sleep approach.As stated in a comment, additionally, the compiler may optimize out an empty loop, and the attempt to pause may be lost. So either you will waste CPU power, or you will not pause at all.
Context
StackExchange Code Review Q#42506, answer score: 90
Revisions (0)
No revisions yet.