Sign in to follow this  
3DModelerMan

How much CPU usage should just an empty game loop have

Recommended Posts

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.

Share this post


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

Share this post


Link to post
Share on other sites
[quote name='Waterlimon' timestamp='1350740570' post='4992146']
I think he meant to use the sleep function to wait until its time for the next frame?
[/quote] Yeah. Or Sleep(0) to give up the remainder of my timeslice.

Share this post


Link to post
Share on other sites
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()
UpdateStuff()
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.

Share this post


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

Share this post


Link to post
Share on other sites
[quote name='Erik Rufelt' timestamp='1350745635' post='4992170']
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.
[/quote]

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

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
[quote name='3DModelerMan' timestamp='1350828531' post='4992441']
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?
[/quote]

What you've got is something similar to a "[url="http://en.wikipedia.org/wiki/Spinlock"]spin loop[/url]", 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.

Share this post


Link to post
Share on other sites
[quote name='Erik Rufelt' timestamp='1350745635' post='4992170']
Use vertical sync in your graphics API instead, which will limit your game to 60 fps if your screen is set to 60 Hz.
[/quote]
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.

Share this post


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

Share this post


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

Share this post


Link to post
Share on other sites
[quote name='Daaark' timestamp='1351174945' post='4993799']
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.
[/quote]

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

Share this post


Link to post
Share on other sites
what the hell people, i asked a similar question months ago [url="http://www.gamedev.net/topic/617810-using-sleep-in-a-game/"]http://www.gamedev.n...leep-in-a-game/[/url]

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

Share this post


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

Share this post


Link to post
Share on other sites
[quote name='L. Spiro' timestamp='1351239576' post='4994067']
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).
[/quote]

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.
[quote name='L. Spiro' timestamp='1351239576' post='4994067']
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.[/quote]
yes, but this wasn't made clear until just a few posts ago, before then, everyone assumed he was working with windows in mind.

[quote name='L. Spiro' timestamp='1351239576' post='4994067']
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
[/quote]

[quote name='slicer4ever' timestamp='1325368347' post='4898536']
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?
[/quote]
[quote name='3DModelerMan' timestamp='1350738770' post='4992138']
How much CPU usage should show when an engine is running an empty game loop?
[/quote]

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.

Share this post


Link to post
Share on other sites
[quote name='L. Spiro' timestamp='1351023545' post='4993187']
Here is why the above post is -3.[list=1]
[*]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.
[list=1]
[*]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.
[/list] [*]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.
[list=1]
[*]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.
[/list]
[/list]

L. Spiro
[/quote]
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

Share this post


Link to post
Share on other sites
[quote name='slicer4ever' timestamp='1351240291' post='4994071']
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.
[/quote]

I'd say the solution you posted in your thread is correct, on desktop PCs, don't care when your app is active, sleep when it's in the background.
The problem usually takes care of itself with vsync. If the user chooses to disable vsync, then they want as high a framerate as possible, which is obviously achieved by never waiting, and with vsync the OS will hopefully not use more CPU than it needs to.
Some games have a separate "limit framerate" option that can be enabled without vsync. If you implement that, and it is active, then you might want to do something other than just spinning on your timer function, just to play nice and allow users that want to decrease CPU usage for whatever reason to do so.

Share this post


Link to post
Share on other sites
[quote name='Washu' timestamp='1351241464' post='4994076']
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.
[/quote]
I agree that just using 100% of the CPU is unlikely to cause damage, and mentioned so in my post.
But I do have recent experiences with overheating on graphics cards (much more common). One of my laptops is only a few years old and has been permanently damaged from overheating to the point where I can’t even turn it on anymore.
However, just dong a while ( true ) loop is not possibly going to cause such a case as you correctly point out.


[quote name='Washu' timestamp='1351241464' post='4994076']
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).
[/quote]
I hope I didn’t come off as implying otherwise.
I just assumed the original poster is doing [i]something[/i] strange because I don’t think a normal empty game loop should otherwise be taking 60% of the CPU.
It turns out he was on Android, which explains that.



slicer4ever, in general a game should be trying to use all resources available.
But it should only be able to reach that point when it is actually a full game, not just an empty loop.
I still don’t see a problem between your replies.
You are on Windows, and while there are things to consider about power usage etc., it is not hugely important for you to consider them. Many games don’t. I have lost hardware because of it, but it is up to you to take those things into consideration on your own will.
I don’t think it is something that needs to be brought up every time this question is asked, so you don’t need to mind so much that it wasn’t mentioned in your post.
You got the correct reply for your needs.
It was just fortuitous that this poster also got the correct reply for his needs, which include battery conservation.


L. Spiro Edited by L. Spiro

Share this post


Link to post
Share on other sites
@lspiro my appologies for my rudeness. The OP never stated his target platform let alone much else. The point i was trying to get across is hes worrying way too much about the little things. Which stinks of someone that does 99% theorizing and 1% coding. I was trying to get across the point that he should code his app and not worry about these things yet. As he gets experience with common headaches hell learn how better to identify them and avoid em.

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