Share via


What's the smallest amount of time I can have a thread sleep while polling that won't slow down the program or computer?

Question

Thursday, November 12, 2009 2:25 PM

for instance

while(true)
{}

runs over and over pretty fast ans slows down the computer

but does

while(true)
Thread.Sleep(1);

do the same thing? what is amount of time to have your thread sleep for that won't impact the performance of the application or computer?

All replies (5)

Thursday, November 12, 2009 3:16 PM âś…Answered | 1 vote

The best way to not impact the computer's performance is to not use sleep.  It is a poor API to use in almost all cases.  I've worked at companies where the use of such a function would get tagged during code reviews.  It causes far more problems than it solves.

The problem is that polling itself is rarely a good idea.  The better option is to use eventing or blocking calls to efficiently pause your app until some condition is true.  Using a synchronization event would allow one part of your app to react to a state change in another part of your app.  While it is waiting the thread is efficiently put to sleep such that it wastes no processor time.  If that is out of the question then use some waitable object like a thread handle or something that you can then use Wait on with a timeout.  Again the thread goes into an efficient sleep until the condition is true or the timeout occurs. 

Note that Thread.Sleep(1) won't work because Sleep relinquishes the thread's timeslice.  The minimum amount of time a thread will actually stall is determined by the internal system timer but is no less than 10 or 25ms (depending upon OS).  There are some special cases but for the most part you should assume that your thread will always stall for at least 10ms.  If the interval you specify is less than the system timer's resolution then you might not block at all otherwise it'll be a multiple (plus the latency).

Michael Taylor - 11/12/09
http://p3net.mvps.org


Thursday, November 12, 2009 3:14 PM

So you're looking for a compromise between slowing your application down or slowing the rest of the system down?

But it's impossible to answer that question without knowing what processing you want to do in the loop...

Can you be more specific?


Thursday, November 12, 2009 4:05 PM

If your objective is to get your CPU as hot as possible, spawn as many threads as you have cores and then use

while (true)
Thread.Sleep(0);

on each thread.

Can't think of any other use for that construct.


Thursday, November 12, 2009 4:23 PM

Well, spinlocks can be extremely useful in some cases - but you don't use Sleep() for those of course.


Friday, November 13, 2009 10:56 PM

Thanks for the detailed answer!