Search code examples
javaprocessorutilization

Lowering CPU utilization in Java programs


I have coded a pretty simple Java 2D game with only two threads - a music player and the game. I noticed when I kick on the game that my CPU utilization shoots up from the 20% range to the 70% range. A lot of the processing I want in the game isn't even implemented yet!

  1. Is this a concern? - shouldn't a simple game not hog so much CPU?

  2. If it is a concern; what are GENERAL coding practices or design patterns to avoid a huge leap in utilization (other than no multithreading)?


Solution

  • If it is a concern; what are GENERAL coding practices or design patterns to avoid a huge leap in utilization (other than no multithreading)?

    Most game engines have a game logic update function which is called 60 times a second, and a drawing function which is called as often as the computer has resources to (but not more than the logic updates).

    The general coding practice here is that you don't want to update the game more than you need to. Try putting a counter in your main loop and seeing how many times in 10 seconds it is called? If you are running more than 60 updates a second, there is no need for this CPU burden!

    It looks like you are not using a game engine that gives you this, so you could hack together a solution: have your main while loop find the current time (Java's DateTime gives you millisecond precision, whcih is good enough), and then compare it to the update time on the last loop. If not enough time has passed, use Thread.sleep() to take the burden off the CPU while your game waits to run its next iteration!

    One last comment:

    (other than no multithreading)

    While having the CPU switch threads causes a little bit of overhead, I don't think using many well-written threads should make the CPU work harder (I'm assuming the sum of the work is the same as with less threads). In fact, if your machine is multi-core it would let your game work faster if there was a part where it needed the CPU (assuming your threads are concurrent instead of blocking one another)!