Search code examples
javasoftware-design2d-games

Game programming - CPU usage of an infinite loop


I want to create a simple 2D game. I don't want to use threads. The programming language will be Java (but could be any language, does not really matter...).

Is it possible to avoid high CPU usage if I use a main loop like while(true)... (infinite loop)?


Solution

  • In a game you typically have a main loop that runs everything. However, in order to avoid doing unnecessary things, it is typical to only update the game at a certain frame-rate (such as 60 Frames Per Second (FPS)).

    Most games accomplish this by causing the CPU to sleep until a new frame needs to be calculated/drawn. In the python game library, pygame, this is done using pygame.time.wait:

    Will pause for a given number of milliseconds. This function sleeps the process to share the processor with other programs. A program that waits for even a few milliseconds will consume very little processor time.