• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Idov

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

22 posts in this topic

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

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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 )

2

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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? 

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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?

0

Share this post


Link to post
Share on other sites

 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?

 

0

Share this post


Link to post
Share on other sites

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 ?

0

Share this post


Link to post
Share on other sites

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

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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

1

Share this post


Link to post
Share on other sites

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.

0

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.

1

Share this post


Link to post
Share on other sites

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.

0

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  
Followers 0