Thursday, January 7, 2016

c++ - CPU usage, game loop and sleep()



I've read about this topic on numerous discussion sites, but I can't seem to find a clear definitive (up-to-date) answer, and hopefully this will me some more insight:


I've read the excellent game loop time article on Fix your timestep!, but it dosn't take any consideration of the CPU usage, so it will run at 100%. My question then, is it BAD to run at 100% CPU in your game loop?



  • If no, why? for example what about gaming on battery-driven devices like laptops? what about computer temperatures/fans/etc, and other windows applications?

  • If yes, why dosn't the article mention it, because surely that would impact it significantly? what is the best way to fix this on desktops/PC - is there only the unreliable sleep()? How would it affect the game loop suggested by the article?



Answer



Running at 100% CPU is not necessarily bad. On the other hand, it can be quite a significant problem. Basically, it depends on what you're running on and how you're running it. It would be best to view a couple of scenarios to show this:


Scenario 1




  • On a dedicated gaming machine, with only the game open


In this case, it is a very good idea to use as much as possible of the CPU for your game. It'll end up running faster, and it won't be stealing CPU from anything that needs it (the system processes will still get what they need, don't worry about that).


Scenario 2



  • On a computer also being used for word, the internet, a couple of Youtube videos (like in that Chrome ad), etc.


In this case, using all of the CPU for your game will cause the user to eject the disk, snap it in two (ignoring the fact that they could get a refund), chuck it in a fire, and then flame your forums. Joking aside, it is never a good idea to use all of the CPU if there's a likelihood that the user will be doing something else with their computer at the same time.


An important thing to consider as well is whether the target has a single or a multi-core computer. With a single-core computer, your game could take up all of the processing power, causing everything else to grind to a halt. On the other hand, with a multi-core computer, unless you're making full use of both cores, it should cause no problem - you'll be taking up one core, but there will be more for the other applications.


At the end of the day, it depends on these sort of issues as to whether using 99% of the CPU time is a good or a bad thing. Intrinsically, it isn't, but there can be cases where it is. Just remember that (on a computer, anyway - games consoles are a different species), it is often up to the machine to virtually allocate CPU time to different applications.



No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...