Sign in to follow this  
Idov

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

Recommended Posts

Idov    210

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 :)

Share this post


Link to post
Share on other sites
Hiwas    5807

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.)  Another option which won't reduce the apparent CPU load, but does in fact basically idle the CPU is to use the assembly instruction 'pause'.  The instruction is used in user space spin locks and basically issues a uop which does nothing except wait for the CPU pipeline to be empty.  Place an inline assembly instruction of this within a loop and the cpu will effectively be doing an increment and compare (for the loop) and then waiting for the pipeline to flush before doing anything else.  This still shows up as busy waiting in performance monitoring but there is effectively no load and in the case of hyperthreading, the other hardware thread is at nearly full utilization of the core while this is happening.

Share this post


Link to post
Share on other sites
Cornstalks    7030

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.

Share this post


Link to post
Share on other sites
Idov    210

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? 

Share this post


Link to post
Share on other sites
Cornstalks    7030

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.

Edited by Cornstalks

Share this post


Link to post
Share on other sites
VildNinja    789

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?

Share this post


Link to post
Share on other sites
frob    44913
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.

Share this post


Link to post
Share on other sites
Idov    210

 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?

 

Share this post


Link to post
Share on other sites
Bacterius    13165

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.

Share this post


Link to post
Share on other sites
galop1n    937

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 ?

Share this post


Link to post
Share on other sites
Idov    210

@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). :)
 

Share this post


Link to post
Share on other sites
EJH    315

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.

Share this post


Link to post
Share on other sites
ApochPiQ    23005

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.

Share this post


Link to post
Share on other sites
EJH    315

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.

Share this post


Link to post
Share on other sites
frob    44913

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.

Share this post


Link to post
Share on other sites
Promit    13246

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.

Share this post


Link to post
Share on other sites
Hodgman    51234

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).

Share this post


Link to post
Share on other sites
Promit    13246

I guess I missed that. When I wrote my profiler, I found that firing at 3ms intervals off a system timer was more than enough, and in fact you could bring down the sampling rate significantly if you were dealing with fairly repetitive processes like games tend to have. Actually my take on that is that it will cost you far more time to freeze your target's threads and walk the stacks than it will to deal with these little timing quirks.

Share this post


Link to post
Share on other sites

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)

There's another such feature, which actually gives a quite good almost-RT behaviour (awesome in theory, in practice not always so) when using waitable timers as proposed by frob. When a waitable object becomes signalled, a thread waiting on it gets its priority temporarily boosted (presumably for 1 time slice, though the docs don't state for how long).

 

The Windows scheduler serves threads from highest priority downwards, serving higher priority threads until none is left, and also interrupts lower priority threads before their time slice has been used up when higher priority threads become ready.

That is, in theory (if nobody has tampered with process priorities, and no disk I/O thread is busy) this ensures that the thread actually runs "immediately" when the timer fires. Even though it doesn't always work quite as good as intended, in any case it's a not-totally-stupid approach that works more often than it doesn't, and it makes using waitable timers as good as you can get.

Share this post


Link to post
Share on other sites
Jason Z    6434

I think the original solution that the OP mentioned will also have the negative impacts that have been discussed throughout this thread.  If he sits in a loop spinning and checking the time elapsed, the thread could be pre-empted immediately before he reaches the desired elapsed time.  That would put his granularity at the mercy of the scheduler too, so I think the many good suggestions that have been given will provide equal precision to what he is currently using...

 

With that said, has the OP tried doing a series of NOP in his loop that he is checking the elapsed time in?  That would allow you to change the granularity of your checking, and reduce the power consumption of the loop at the same time.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this