Skip to main content
GameDev.net gamedev.net
🔒 Locked

Making a "Busy Loop" not consume that much CPU (without Sleep)

Started by Idov May 18, 2013 at 3:13 PM 21 replies 25.4k views
Original Post
Idov
Idov

Hi!

I want to measure a very small period of time ( let's say 0.2 ms).

In order to do this, I'm using busy loop which checks whether or not we waited in the busy loop for the requested time like this:

double startTime = MeasureTime();

double endTime = MeasureTime();

while (endTime - startTime < timeToWait)
{

endTime = MeasureTime();
}

I'd like to use some functions which don't use much CPU in that loop in order to ease the CPU load.

which functions should I use?

thanks :)

Cornstalks
Cornstalks

You can yield the thread's time slice. This will reduce CPU usage while still being higher "precision" than sleep(). There are several ways to do it:

C++11 threads: std::this_thread::yield()

C11 threads: thrd_yield()

Boost threads: boost::this_thread::yield()

Pthreads: pthread_yield()

Win32 threads: Sleep(0)

Java: Thread.yield()

C#: Thread.Yield()

If you're using another language, you'll have to look up how to do it in that language.

Matias Goldberg
Matias Goldberg

Win32 threads: Sleep(0)

No God, NO!

Use SwitchToThread to yield (supported since Win XP)

Sleep( 0 ) is a terrible way of yielding. If you're looking to avoid consuming CPU cycles (i.e. lower power usage) prefer Sleep( 1 ) over Sleep( 0 )

Cornstalks
Cornstalks

While yield is a valid way to reduce the load, it is still effectively a sleep by a different name. (On windows it is usually just a Sleep( 0 ) call anyway.)

Sleep(0) on Windows is treated as a special case. I'm not sure I'd call yield "sleep by a different name," though, because they have some important differences.


Win32 threads: Sleep(0)

No God, NO!

Use SwitchToThread to yield (supported since Win XP)

Sleep( 0 ) is a terrible way of yielding. If you're looking to avoid consuming CPU cycles (i.e. lower power usage) prefer Sleep( 1 ) over Sleep( 0 )

The OP wants to sleep for 0.2 milliseconds... Sleep(1) will overshoot that by a ton. SwitchToThread() is probably preferable (thanks for pointing it out to me!), but I can't see any significant difference between it and Sleep(0) in the MSDN docs. Maybe I'm missing something.

Idov
Idov

Ok, thanks!
But as far as I understand Sleep(0), SwitchToThread, etc. will only switch to another thread if there is another thread waiting to use the CPU, but if there isn't one - it won't do anything.

I will try to use it, but what do you say about using functions such as printf() that uses the IO devices and not the CPU in order to achieve my goal?

Cornstalks
Cornstalks

Ok, thanks!
But as far as I understand Sleep(0), SwitchToThread, etc. will only switch to another thread if there is another thread waiting to use the CPU, but if there isn't one - it won't do anything.

That's true, yielding typically only helps if other threads are available for running. But remember, on modern computers there are often hundreds of threads in existence, and the OS can idle the CPU in its own threads if there isn't work to be done (so the OS threads can potentially eat the remaning time with proper CPU idling). I recall a few times I had a program doing a loop that went from about 100% CPU usage to near 0% usage after putting a single yield in it (I don't recall the exact amount it dropped by, but it was significant). [Edit: I've been thinking about this last statement for the past few days and I'm actually second guessing myself; it's possible I did a sleep(1) instead of an actual yield]

I will try to use it, but what do you say about using functions such as printf() that uses the IO devices and not the CPU in order to achieve my goal?

Blocking on IO devices might work, but it's a pretty uncommon way of doing things. Also, once you get in the sub-millisecond range (like you are), blocking on IO devices might block for longer than you want.

VildNinja
VildNinja

But as far as I understand Sleep(0), SwitchToThread, etc. will only switch to another thread if there is another thread waiting to use the CPU, but if there isn't one - it won't do anything.

Unless you're writing code for an isolated system, there is almost always another thread/task waiting to use the cpu.

As far as I know you will not get the desired effect from the loop, since most system timers are no more precise than ~10 ms, even though you can get the number represented in nanoseconds. So unless you are using a method to get a very accurate time, you might as well use sleep.

Depending on what you are doing I would recommend you to change the flow of the program, such that you don't have to use a loop to wait for 0.2 ms, rather wait until a certain condition set elsewhere in your code is true. Is this just a theoretical question or are you working on something in particular?

frob
frob
One of the better options for a short wait is to use the WaitableTimer object. It can be set in (approximately) 200 nanosecond increments, then use WaitForSingleObject (or similar) to wait for it to trigger. There is more on MSDN. Be sure to pass a NEGATIVE time value so it knows the value is relative, otherwise you'll be setting timers that trigger back in the year 1600 or so.

Ultimately, even this solution isn't guaranteed. Windows simply is not a real time operating system. With a waitable timer you will probably get woken up about when you expect, but your thread can be suspended at any time, and the granularity for resuming threads is roughly 10ms. This is just a fact we get to live with.
Idov
Idov

VildNinja:

As far as I know you will not get the desired effect from the loop, since most system timers are no more precise than ~10 ms, even though you can get the number represented in nanoseconds. So unless you are using a method to get a very accurate time, you might as well use sleep.

I'm using QueryPerformanceCounter in order to measure time in a higher resolution. :)


CornStalks:

That's true, yielding typically only helps if other threads are available for running. But remember, on modern computers there are often hundreds of threads in existence, and the OS can idle the CPU in its own threads if there isn't work to be done (so the OS threads can potentially eat the remaning time with proper CPU idling). I recall a few times I had a program doing a loop that went from about 100% CPU usage to near 0% usage after putting a single yield in it (I don't recall the exact amount it dropped by, but it was significant).

I just tried using Sleep(0). It didn't have any effect :/


Frob:

One of the bester options for a short wait is to use the WaitableTimer object. It can be set in (approximately) 200 nanosecond increments, then use WaitForSingleObject (or similar) to wait for it to trigger. There is more on MSDN. Be sure to pass a NEGATIVE time value so it knows the value is relative, otherwise you'll be setting timers that trigger back in the year 1600 or so.


I will sure try it, but how is it possible?
I've always been told that windows is not a RT system and it can't wait for periods shorter than 1 ms... Is it wrong?

Bacterius
Bacterius


But as far as I understand Sleep(0), SwitchToThread, etc. will only switch to another thread if there is another thread waiting to use the CPU, but if there isn't one - it won't do anything.

And even if that were the case, if there is no thread waiting to use the CPU, what is the problem? Go ahead. Sleep instructions don't make the processor do any work, consuming near zero power. Just because it shows 100% utilization doesn't mean it's actually doing any work. The problem with sleeping loops isn't the processor utilization (despite many anxious people wondering why their programs are having such high processor usage) but rather than accuracy of the sleep instruction, which is pretty pathetic (16ms last time I checked).


I've always been told that windows is not a RT system and it can't wait for periods shorter than 1 ms... Is it wrong?

That's not quite true. The correct statement would be: Windows doesn't give you any guarantees as to when your program gets a slice from the scheduler. That's it. So the best you can do, as frob said, is use the most accurate feedback mechanism available, which is guaranteed by the OS to be set as soon as it can, and read back the timer whenever your process gets to run (without sleeping). Then, when you've got no more work left, you yield. That doesn't mean you get to run your thread every 200 nanoseconds, it means that the OS will do its best to handle your timer with 200 nanosecond accuracy (and it can do that far, far better than your program can, being the operating system and all that) and let you get the results without having to sleep.

“If I understand the standard right it is legal and safe to do this but the resulting value could be anything.”
Hodgman
Hodgman

My experience on Windows:

YieldProcessor() -- same as _mm_pause etc, just an energy efficient NOP. Great for hyperthreaded CPUs or ones with energy efficiency modes!

SwitchToThread() -- politely give up your timeslice to another thread that's ready to use your core right now. Does not consider threads queued up on other cores.

Sleep(0) -- Will switch to any thread that isn't of lower priority than yours. If no other threads are ready, you'll at least go for a run through the OS scheduler for a moment.

Sleep(1) -- really truely give up your core at least for a whole timeslice.

My busy-wait functionality tries each of these an arbitrary number of times in this order, but also checks a "task queue" in between each attempt to sleep/stall, to see if I can use the thread for something useful instead of sleeping/stalling.

@Idov, what's the reason behind needing to stall a thread for such a short period in the first place?

I've always been told that windows is not a RT system and it can't wait for periods shorter than 1 ms... Is it wrong?

...accuracy of the sleep instruction, which is pretty pathetic (16ms last time I checked).

Windows provides timeBeginPeriod/timeEndPeriod to change the scheduling quantum. By default it's 15ms IIRC, but a lot of "realtime" apps use these functions to change it to 1ms (which yes, is the lowest it can be set to). This is a system-wide setting though, and decreasing the quantum can have a negative effect across the whole system in exchange for making it a little bit more real-time-ish.

Off topic: IIRC, there's also a rule in the scheduler where if a thread has been starved for 5 seconds, it will be boosted to the highest priority to ensure it gets at least 1 slice around once per 5 seconds (which is a very weak guarantee compared to what actual RT OS's give you laugh.png)

galop1n
galop1n

Why create a busy loop that will always consume CPU ? Here a single line to do this, and it is self documented std::this_thread::wait_for( std::chrono::milliseconds( 1u ) ); This internally use WaitForSingleObject with the visual studio 2012 implementation.

Also, waiting for less than one millisecond is likely to not do much because it do not exist such precision in the system. You can read the cpu clock with some intrinsic or use QueryPerformanceCounter, but the first one is unlikely to be useful because it may be inconsistent between cores and modern CPU can vary their frequency, and the second one is in fact quite cycle heavy, so not really a good choice for a spin loop.

Why do you need to wait for a so short period of time ?

Idov
Idov

@Hodgman & galop1n:
I'm trying to sample another process (memory, stack, etc) and I'm checking the boundaries of what I can and cannot do (without using all the resources of the computer). :)

Idov
Idov

Hi,
I tried using Waitable Timers like in this example:
http://msdn.microsoft.com/en-us/library/ms687008.aspx

But it seems that the event is signaled only after 1 milisecond and after not the time I specified...
I tried using:
double timeoutMicro = 400;
liDueTime.QuadPart = -1 * timeoutMicro * 10;

EJH
EJH

Can anyone explain why exactly using Sleep() or Yield() is 'bad'? I haven't seen any convincing arguments. I've used Sleep() in threads before with zero side effects and it gave substantial CPU reduction. For example, it reduced a single core sitting at ~50% while idle to about ~4% while idle.

ApochPiQ
ApochPiQ

It's only "bad" in the sense that it doesn't really provide any guarantee of how long your thread will be inactive. Relying on it for timing is kind of like relying on a sundial to count seconds.

EJH
EJH

Ahh ok. Yeah I would never use it for any type of timing. But for a thread that just randomly consumes inputs with no dependencies it works just fine.

frob
frob

Ahh ok. Yeah I would never use it for any type of timing. But for a thread that just randomly consumes inputs with no dependencies it works just fine.

And that's the issue with the whole discussion. The OP wrote he wants to wait "a very small period of time ( let's say 0.2 ms)."

No matter what solution he tries there is no reliable solution for it under Windows. He could fill his code with NOP or _mm_pause or , and at 0.19ms the operating system could suddenly decide to swap out his process for 30ms or more.

Idle spinning is usually not a good thing.

If you must wait, it is usually best to create some sort of event or trigger (such as a semaphore, a memory resource notification, a thread, a waitable timer, or SOMETHING) and then sleep. You will eventually get woken up, hopefully at a time very nearly when you asked to be suspended, but there are no guarantees as Windows is not a real time OS.

Promit
Promit

I'd like to point out that nobody has asked why the OP would like to inject a 0.2ms pause in his application. Why that length of time? How crucial? What is the point of this whole endeavor? This smells like a bad idea out of the gate, nevermind how you'd pull it off.

SlimDX | Ventspace Blog | Twitter | Diverse teams make better games. I am currently hiring capable C++ engine developers in Baltimore, MD.
Hodgman
Hodgman


I'd like to point out that nobody has asked why the OP would like to inject a 0.2ms pause in his application.

Yeah they have tongue.png Looks like he's trying to make a sampling profiler:


I'm trying to sample another process (memory, stack, etc) and I'm checking the boundaries of what I can and cannot do (without using all the resources of the computer).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.