Jump to content

  • Log In with Google      Sign In   
  • Create Account


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


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
23 replies to this topic

#1 Idov   Members   -  Reputation: 196

Like
0Likes
Like

Posted 18 May 2013 - 09:13 AM

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



Sponsor:

#2 Cornstalks   Crossbones+   -  Reputation: 6966

Like
5Likes
Like

Posted 18 May 2013 - 09:22 AM

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.


Edited by Cornstalks, 18 May 2013 - 09:39 AM.

[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#3 AllEightUp   Moderators   -  Reputation: 4109

Like
0Likes
Like

Posted 18 May 2013 - 10:06 AM

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.



#4 Matias Goldberg   Crossbones+   -  Reputation: 3007

Like
2Likes
Like

Posted 18 May 2013 - 10:14 AM

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 )



#5 Cornstalks   Crossbones+   -  Reputation: 6966

Like
0Likes
Like

Posted 18 May 2013 - 11:00 AM

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.


[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#6 Idov   Members   -  Reputation: 196

Like
0Likes
Like

Posted 18 May 2013 - 11:22 AM

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? 



#7 Cornstalks   Crossbones+   -  Reputation: 6966

Like
0Likes
Like

Posted 18 May 2013 - 11:34 AM

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, 28 May 2013 - 04:57 PM.

[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#8 VildNinja   Members   -  Reputation: 420

Like
0Likes
Like

Posted 18 May 2013 - 11:59 AM

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?



#9 frob   Moderators   -  Reputation: 18832

Like
3Likes
Like

Posted 18 May 2013 - 12:05 PM

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.
Check out my personal indie blog at bryanwagstaff.com.

#10 Idov   Members   -  Reputation: 196

Like
0Likes
Like

Posted 18 May 2013 - 12:17 PM

 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?

 



#11 Bacterius   Crossbones+   -  Reputation: 8135

Like
3Likes
Like

Posted 18 May 2013 - 02:27 PM

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.


The slowsort algorithm is a perfect illustration of the multiply and surrender paradigm, which is perhaps the single most important paradigm in the development of reluctant algorithms. The basic multiply and surrender strategy consists in replacing the problem at hand by two or more subproblems, each slightly simpler than the original, and continue multiplying subproblems and subsubproblems recursively in this fashion as long as possible. At some point the subproblems will all become so simple that their solution can no longer be postponed, and we will have to surrender. Experience shows that, in most cases, by the time this point is reached the total work will be substantially higher than what could have been wasted by a more direct approach.

 

- Pessimal Algorithms and Simplexity Analysis


#12 Hodgman   Moderators   -  Reputation: 27543

Like
5Likes
Like

Posted 19 May 2013 - 03:13 AM

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)


Edited by Hodgman, 19 May 2013 - 03:34 AM.


#13 galop1n   Members   -  Reputation: 226

Like
0Likes
Like

Posted 19 May 2013 - 04:48 AM

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 ?



#14 Idov   Members   -  Reputation: 196

Like
0Likes
Like

Posted 19 May 2013 - 10:10 AM

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



#15 Idov   Members   -  Reputation: 196

Like
1Likes
Like

Posted 19 May 2013 - 02:32 PM

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;
 



#16 EJH   Members   -  Reputation: 314

Like
0Likes
Like

Posted 20 May 2013 - 10:03 AM

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.



#17 ApochPiQ   Moderators   -  Reputation: 14252

Like
0Likes
Like

Posted 20 May 2013 - 10:07 AM

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.



#18 EJH   Members   -  Reputation: 314

Like
0Likes
Like

Posted 20 May 2013 - 11:14 AM

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.



#19 frob   Moderators   -  Reputation: 18832

Like
0Likes
Like

Posted 20 May 2013 - 11:45 AM

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.


Check out my personal indie blog at bryanwagstaff.com.

#20 Promit   Moderators   -  Reputation: 6077

Like
0Likes
Like

Posted 20 May 2013 - 11:50 AM

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.






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS