How much CPU usage should just an empty game loop have
#1 Members - Reputation: 534
Posted 20 October 2012 - 07:12 AM
#2 Members - Reputation: 1054
Posted 20 October 2012 - 07:33 AM
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.
Hobby: Game Developer
Currently employed as: Sr. Sharepoint Developer in Afghanistan
#5 Members - Reputation: 1007
Posted 20 October 2012 - 08:32 AM
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.
#6 GDNet+ - Reputation: 516
Posted 20 October 2012 - 08:59 AM
So you might want to consider other alternatives when you need to wait for less than 15 ms.
#7 Members - Reputation: 1985
Posted 20 October 2012 - 09:07 AM
For casual games and window mode Sleep might be a good choice.
#8 Members - Reputation: 534
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.
#9 Members - Reputation: 534
Posted 21 October 2012 - 08:08 AM
#10 Members - Reputation: 1054
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.
Hobby: Game Developer
Currently employed as: Sr. Sharepoint Developer in Afghanistan
#11 Members - Reputation: 1408
Posted 22 October 2012 - 05:05 AM
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.Use vertical sync in your graphics API instead, which will limit your game to 60 fps if your screen is set to 60 Hz.
Leave it as an option that can be enabled.
#12 Members - Reputation: 302
Posted 22 October 2012 - 10:45 AM
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.
[ current projects' videos ]
[ Zolo Project ]
I'm not mean, I just like to get to the point.
#13 Crossbones+ - Reputation: 5164
Posted 23 October 2012 - 02:19 PM
- 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
I spent most of my life learning the courage it takes to go out and get what I want. Now that I have it, I am not sure exactly what it is that I want. - L. Spiro 2013
L. Spiro Engine: http://lspiroengine.com
L. Spiro Engine Forums: http://lspiroengine.com/forums
#15 Members - Reputation: 3503
Posted 25 October 2012 - 08:22 AM
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.
#17 Crossbones+ - Reputation: 1448
Posted 26 October 2012 - 01:38 AM
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.
#18 Crossbones+ - Reputation: 5164
Posted 26 October 2012 - 02:19 AM
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
I spent most of my life learning the courage it takes to go out and get what I want. Now that I have it, I am not sure exactly what it is that I want. - L. Spiro 2013
L. Spiro Engine: http://lspiroengine.com
L. Spiro Engine Forums: http://lspiroengine.com/forums
#19 Crossbones+ - Reputation: 1448
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.
yes, but this wasn't made clear until just a few posts ago, before then, everyone assumed he was working with windows in mind.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
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.
#20 Senior Moderators - Reputation: 3113
Posted 26 October 2012 - 02:51 AM
While I agree with the sentiment of your post, there are several factual inaccuracies present that need to be addressed: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
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






