• Create Account

## How much CPU usage should just an empty game loop have

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.

23 replies to this topic

### #13DModelerMan  Members

1173
Like
0Likes
Like

Posted 20 October 2012 - 07:12 AM

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.

### #2slayemin  Members

5630
Like
2Likes
Like

Posted 20 October 2012 - 07:33 AM

Your CPU usage should be around 0-1%.

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.

### #3Waterlimon  Members

4372
Like
1Likes
Like

Posted 20 October 2012 - 07:42 AM

I think he meant to use the sleep function to wait until its time for the next frame?

o3o

### #43DModelerMan  Members

1173
Like
0Likes
Like

Posted 20 October 2012 - 07:58 AM

I think he meant to use the sleep function to wait until its time for the next frame?

Yeah. Or Sleep(0) to give up the remainder of my timeslice.

### #5Waterlimon  Members

4372
Like
3Likes
Like

Posted 20 October 2012 - 08:32 AM

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.

simplified version:

Timer
while running do
{
Timer.start()
Timer.stop()
sleep(FrameLenght - min(FrameLenght,Timer.GetTimeElapsed())) //min() to not go negative, FrameLenght is 1 second / FPS converted to whatever sleep takes in (ms?)
}

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.

o3o

### #6nife87  Members

520
Like
7Likes
Like

Posted 20 October 2012 - 08:59 AM

POPULAR

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.

### #7Erik Rufelt  Members

5901
Like
1Likes
Like

Posted 20 October 2012 - 09:07 AM

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.

### #83DModelerMan  Members

1173
Like
0Likes
Like

Posted 20 October 2012 - 02:06 PM

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.

### #93DModelerMan  Members

1173
Like
0Likes
Like

Posted 21 October 2012 - 08:08 AM

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?

### #10slayemin  Members

5630
Like
1Likes
Like

Posted 21 October 2012 - 09:28 AM

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.

### #11larspensjo  Members

1561
Like
1Likes
Like

Posted 22 October 2012 - 05:05 AM

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.

Leave it as an option that can be enabled.
Current project: Ephenation.
Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/

### #12freeworld  Members

341
Like
-8Likes
Like

Posted 22 October 2012 - 10:45 AM

Depends on the platform. If the target is plugged into the wall then it should be eating up 99-100% im sure any reason you have for limiting it is mislead and very possibly dumb.

Now if this is on a platform that has battery life. Never mind still your main loop doesnt matter. Your app is gonna run when its on. Its what you do in that loop that matters.

Now stop with the silly questions and code something.
[ dev journal ]
[ current projects' videos ]
[ Zolo Project ]
I'm not mean, I just like to get to the point.

### #13L. Spiro  Members

24826
Like
8Likes
Like

Posted 23 October 2012 - 02:19 PM

POPULAR

Here is why the above post is -3.
• 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.
• If your PC is burning cycles needlessly it costs money. A sleeping PC < a normal-use PC < a dedicated Battlefield 3 PC in terms of daily expenses to your electricity bill.
• 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

### #143DModelerMan  Members

1173
Like
1Likes
Like

Posted 25 October 2012 - 07:48 AM

Thanks everyone. I've got it using up between 3-4% CPU and running locked at 60 FPS now. @freeworld This engine is going to run on Android also, so battery life is VERY important.

### #15MrDaaark  Members

3556
Like
1Likes
Like

Posted 25 October 2012 - 08:22 AM

LOL @ the naive power consumption attitude.

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.

### #163DModelerMan  Members

1173
Like
0Likes
Like

Posted 25 October 2012 - 02:49 PM

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.

Thanks. I'm gonna read throuh all of those.

### #17slicer4ever  GDNet+

6355
Like
0Likes
Like

Posted 26 October 2012 - 01:38 AM

what the hell people, i asked a similar question months ago http://www.gamedev.n...leep-in-a-game/

and received a complete opposite response to the usage of sleep.

To summaries what i was told: The cpu is a resource, use it.

Edited by slicer4ever, 26 October 2012 - 01:39 AM.

Check out https://www.facebook.com/LiquidGames for some great games made by me on the Playstation Mobile market.

### #18L. Spiro  Members

24826
Like
3Likes
Like

Posted 26 October 2012 - 02:19 AM

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.

L. Spiro

### #19slicer4ever  GDNet+

6355
Like
0Likes
Like

Posted 26 October 2012 - 02:31 AM

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.
Check out https://www.facebook.com/LiquidGames for some great games made by me on the Playstation Mobile market.

### #20Washu  Senior Moderators

7713
Like
2Likes
Like

Posted 26 October 2012 - 02:51 AM

Here is why the above post is -3.

• 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.
• If your PC is burning cycles needlessly it costs money. A sleeping PC < a normal-use PC < a dedicated Battlefield 3 PC in terms of daily expenses to your electricity bill.
• 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

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.