How much CPU usage should show when an engine is running an empty game loop? An (almost) infinite loop like the game loop eats up more CPU time than other programs, but how much is too much? Should I be adding sleep calls to it and limiting updates to 60hz? Because it's showing 60% CPU usage in the task manager as opposed to 10-14% when the game isn't running.

Don't use sleep calls. Instead, calculate how much time has elapsed and update when you've passed that time span.
If you want to update 60 times a second, then there are 1000ms in a second. So, the time span to process a frame should be 1000/60 = 16.66666666666667 ms
When your game loop starts, record the time. Your loop processing will complete long before 16.66ms has elapsed, but as you add more logic, the time it takes will increase. So, you want to make sure that before starting the next frame, the current time >= last frame time + 16.6666ms
this would lock your FPS at a max of 60. But, when you're moving stuff around in your game, don't move it a fixed amount each frame. Move it based on how much time has elapsed between frames. That way, if your actual frame rate increases or decreases, your game state model is still running according to real time.

If you process your next frame when a set time span has elapsed, you should get about 0-1% cpu usage since it takes next to no time to process your update loop.

It seems like using sleep() is ok, but you should measure the time it takes to process your updates, so that if they take long, you need to sleep less and if they dont take much time you can sleep longer to keep a consistent FPS.

You might want to have it measure longer periods of time in case the loop and timing itself takes a ridiculous amount of time for no reason (i dont think thats needed but i could be wrong) or catch up if its laggy for some time by doing extra updates after.

Be careful when using Win32's Sleep. The call might return instantly or sleep for up to ~15 ms when calling Sleep(n), where 0 <= n <= 15. This happens because the default tick resolution is (1/64) s = 15.625 ms, which can be altered (only for the entire system!) using timeBeginPeriod/timeEndPeriod.
So you might want to consider other alternatives when you need to wait for less than 15 ms.

If you're writing a realtime game and want smooth animation, avoid limiting the framerate with Sleep. Use vertical sync in your graphics API instead, which will limit your game to 60 fps if your screen is set to 60 Hz. Usually DirectX and OpenGL nowadays handle vertical sync by sleeping to avoid high CPU usage if your game processing completes with time to spare before screen refresh. Internally they will use some system-level sleep that is made to wake in time for the swap, whereas an application level sleep can cause tearing and stuttering in your animation, as nife87 explained, and you probably want vertical sync anyway to make everything look smooth even if you don't care about sleep.

If you're writing a realtime game and want smooth animation, avoid limiting the framerate with Sleep. Use vertical sync in your graphics API instead, which will limit your game to 60 fps if your screen is set to 60 Hz. Usually DirectX and OpenGL nowadays handle vertical sync by sleeping to avoid high CPU usage if your game processing completes with time to spare before screen refresh. Internally they will use some system-level sleep that is made to wake in time for the swap, whereas an application level sleep can cause tearing and stuttering in your animation, as nife87 explained, and you probably want vertical sync anyway to make everything look smooth even if you don't care about sleep.

For casual games and window mode Sleep might be a good choice.

Yeah I'll have vsync setup for sure. I'm talking about the game loop though not the rendering loop.

Okay. I used an event and WaitForSingleObject to wait for a maximum of 100 ms when the game doesn't have focus. Now when the game doesn't have focus it uses up almost no CPU time at all. When nothing is running except windows I have 10-20% CPU usage. The game loop doing nothing at all (I event commented out every single call to update a subsystem) shows 50-60% CPU usage. So my game loop accounts for about 40-50%. What's weird though is that when the game is running logic it stays at just about exactly 50%. Why would this be? I'm doing some more work, but my CPU usage doesn't end up fluctuating as high. Could it just be a fluke and the OS is doing stuff behind the scenes? Or could it be because I send tasks off to other cores with a thread pool?

Okay. I used an event and WaitForSingleObject to wait for a maximum of 100 ms when the game doesn't have focus. Now when the game doesn't have focus it uses up almost no CPU time at all. When nothing is running except windows I have 10-20% CPU usage. The game loop doing nothing at all (I event commented out every single call to update a subsystem) shows 50-60% CPU usage. So my game loop accounts for about 40-50%. What's weird though is that when the game is running logic it stays at just about exactly 50%. Why would this be? I'm doing some more work, but my CPU usage doesn't end up fluctuating as high. Could it just be a fluke and the OS is doing stuff behind the scenes? Or could it be because I send tasks off to other cores with a thread pool?

What you've got is something similar to a "spin loop", which is commonly used in multithreading spin and wait until a resource becomes available again. Except, it's really just an infinite loop. It'll run as fast as it can, provided the operating system gives it all the CPU resources it can.

I'm guessing that your computer has a processor with two cores. The spin loop is running in a thread on one of those cores and maxing it out at 100%, and because you've got two cores, one of which is 100% and the other at 0%, the average CPU usage is almost exactly 50% (with noise from other processes/threads causing fluxuations). If you're using task manager to measure CPU usage, you can view each core independently: View -> CPU History -> One Graph per CPU

You'll want your game loop to return the CPU to the OS until a desired time span has elapsed (which I mentioned above). You can use the Sleep function and probably get away with it without having any issues.

Use vertical sync in your graphics API instead, which will limit your game to 60 fps if your screen is set to 60 Hz.

There is a drawback using VSYNC . It will effectively sleep until next sync, which is sometimes fine. Except when your game refresh rate is slower than 60 fps, it will still wait until the next sync, and you will miss a full cycle. 60 fps equals a sync every 16.7ms. If you need 20ms for a cycle, the delay will be until the next sync again, in total of 33ms.

Battery life is not your only concern, so just because something plugs into a wall does not mean there is no other possible reason not to want to reduce the CPU load.

If your PC is burning cycles needlessly it runs hot. This can cause your fans to overwork themselves and eventually shut down, allowing the CPU to overheat, possibly causing permanent damage. Though a main loop in itself is unlikely to cause this.

There are other applications running besides your game (and its main loop). If your main loop takes 99% of your CPU, other applications starve. You won’t get that ever-so-important Google Talk message notification until hours later when the game shuts down.

If your target device has a battery, you need to give time back to the operating system as much as you can so that it can conserve that battery.

Your loop isn’t run when it’s run. It is run when you tell it to run. For iOS this generally means a setting on the display link to trigger at, say, 30 FPS. This conserves battery life, whereas telling it to trigger 60 times per second wastes it.

100% is not a good thing. It takes huge chunks of time off the lifespan of your hardware. I've had parts that were literally melted right through. I've had green boards grow huge yellow circles around their hot chips. I'm sure anyone who routinely renders 3d scenes from a DCC package knows this all too well.

As for mobile, the difference between good and bad programming makes a world of difference. My device can stream 720p video from youtube or netflix for upwards of 8-10 hours. I can play 3d games that rival my PS3 graphically for hours on end. But there are some apps, like this one low resolution 2D mahjongg game I used to have that would eat through the battery in minutes!

3DModelerMan, if you are targeting android, there are some articles on their site about tricks on how to do common tasks to reduce the drain on the battery.

I get the same message from both threads: Don’t use sleep() unless the game is in the background.
nife87 and Erik Rufelt correctly warned against it here just as others had in your thread (by Bacterius for example).

You should note that this person is asking for advice on a mobile platform (Android) where battery life is a concern, and in this case “the CPU is a resource so use it” doesn’t have the same weight.
He is also asking about just a main loop, not including rendering, physics, etc.
Basically, you got the correct answer for your situation and he got the correct answer for his. You don’t share the same situation so you should not expect exactly the same answer.

I get the same message from both threads: Don’t use sleep() unless the game is in the background.nife87 and Erik Rufelt correctly warned against it here just as others had in your thread (by Bacterius for example).

Yes, but both arn't advocating against lower cpu usage, just that sleep is not an accurate method for timing to return to a thread within a fixed time length.many people here are still advocating that using minimum cpu is best, whearas in my thread, many people told me that worrying about cpu utilization is a non-issue because it's a resource that should be used.

You should note that this person is asking for advice on a mobile platform (Android) where battery life is a concern, and in this case “the CPU is a resource so use it” doesn’t have the same weight.

yes, but this wasn't made clear until just a few posts ago, before then, everyone assumed he was working with windows in mind.

He is also asking about just a main loop, not including rendering, physics, etc.Basically, you got the correct answer for your situation and he got the correct answer for his. You don’t share the same situation so you should not expect exactly the same answer.

L. Spiro

is their an alternative to sleep that doesn't cause the cpu to be used constantly, or should i simply not care that i'm utilizing 100% of the resources?

How much CPU usage should show when an engine is running an empty game loop?

these are essentially the same questions, posed at the start of both threads, but what i took away from my thread was that the cpu is just another resource, use it to it's fullest, and here, i'm taking away that the game should use as little cpu resource as possible, to avoid unnecessary damage to user hardware.

Battery life is not your only concern, so just because something plugs into a wall does not mean there is no other possible reason not to want to reduce the CPU load.

If your PC is burning cycles needlessly it runs hot. This can cause your fans to overwork themselves and eventually shut down, allowing the CPU to overheat, possibly causing permanent damage. Though a main loop in itself is unlikely to cause this.

There are other applications running besides your game (and its main loop). If your main loop takes 99% of your CPU, other applications starve. You won’t get that ever-so-important Google Talk message notification until hours later when the game shuts down.

If your target device has a battery, you need to give time back to the operating system as much as you can so that it can conserve that battery.

Your loop isn’t run when it’s run. It is run when you tell it to run. For iOS this generally means a setting on the display link to trigger at, say, 30 FPS. This conserves battery life, whereas telling it to trigger 60 times per second wastes it.

L. Spiro

While I agree with the sentiment of your post, there are several factual inaccuracies present that need to be addressed:

1. If your fans are spinning up when you run a while(true); then you have a serious problem. That is not to say that you should run such a loop, but the idea that 100% CPU usage is going to overheat and melt your machine is ludicrous. That may have been true a long time ago, on hardware from the 1980s, but if your machine is melting down on a while(true); loop you've got a lot bigger issues than said loop.

2. Windows (and in fact pretty much every operating system you will find on PC class hardware) is a pre-emptive multitasking operating system. This means every single thread is allocated a slice of the CPU's time and when that slice of time is up it is preempted and another thread scheduled. All processes, in Windows, will get their own slice of time and a chance to do their work. If it were otherwise then your game would be unable to render, as all of the actual work happens during the driver/kernel's time slice. You can resource starve threads, but that's an issue for your own process and not for other processes that are running concurrently, and if you screw around with thread priorities you can increase your timeslice, but usually only to your own detriment (if you starve the kernel's threads... most of the work you schedule just doesn't get done).

3. While a sleeping PC certainly costs less to run an a running PC, a "Battlefield 3 PC" might cost less to run than a "normal" PC. Why? Because the power supply that you would put in such a machine (say 1000w) is actually much more efficient than what you will find in your typical Dell. An example: My PC, which was a powerful beast when I built it, was recently upgraded to an even more powerful set of hardware. However, during general usage its power usage DROPPED (traced by my UPS, which feeds information and usage stats back to the machine) on average. This is because the power supply, amongst other things, is much more efficient at its job.

Now, on to CPU usage and your game loop:In general, if you are done with your timeslice you should probably wait (using one of those efficient timing mechanisms that are not sleep) for the appropriate amount of time so that you can wake up and get going again shortly. Sleep does more than simply tell your thread to "wait for N seconds (or milliseconds)", it surrenders your timeslice entirely, and when you get scheduled again is entirely up in the air. In otherwords, sleep simply tells the operating system to schedule your thread anytime AFTER the amount of time you indicate. When that "after" is is entirely unspecified. You can also use features such as v-sync to allow the system to surrender your timeslice when you call present, etc. This allows you to defer the choice to the end user, as you can provide options to disable v-sync thus allowing them to consume more power (for likely little gain).

Windows includes high performance waitable timers, which are usually far more than sufficient for the needs of a simple game loop that needs to run N times a second.

On mobile hardware this is a harder problem, because many mobile platforms dont' expose such timers, or the hardware doesn't necessarily support it. However the typical "energy efficient" mechanisms I've seen typically involve a scheduled timer that goes off which triggers rendering events, etc. or mechanisms that involve getting notified when the screen is going to update and taking appropriate actions then (for rendering). These kinds of mechanisms allow the hardware, and operating system, to take advantage of the ability to dynamically power on and off various components in order to conserve and extend battery life. In fact, many of the modern mobile processors support the ability to power off components OF the CPU in order to enable them to achieve even greater energy savings, thus extending battery life.

Edited by Washu, 26 October 2012 - 03:00 AM.

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.ScapeCode - Blog | SlimDX