I was wondering if there is any possible harm when my game loop runs as fast as the system allows?
I currently have a loop, that, by measuring passed time in nanoseconds, runs the game logic and rendering logic at predefined speeds without a problem. In fact any logic I do in the loop is clocked to a certain amount of calls each second.
The loop itself though just runs about as fast as it likes to which comes up to around 11.7 million loops a second on my machine.
Loop (simple pseudocode):
while(!isGameOver){
if(canPollInputs){
pollInputs()
}
while(canStepLogic){
stepLogic()
}
if(canRender){
render()
}
}
My question is basically if that simple loop, if its not running at a controlled speed, can do any harm to a system?
Edit: That means my logic is running 30 times a second (30 tps), my renderer is running at 60 fps, I'm polling inputs a 100 times a second and there's also some logic to cope with logic or rendering taking longer than expected. But the loop itself is not throttled.
Edit:
Using Thread.sleep()
to e.g. Throttle the main loop down to 250 loops per second leads to a reduction but the loops runs at around 570 loops per second instead of the desired 250 (will add code when I'm at my desktop machine..)
Edit: Here we go, a working java gameloop in order to clarify things. Also feel free to use it but don't claim it yours ;)
private void gameLoop() {
// Time that must elapse before a new run
double timePerPoll = 1000000000l / targetPPS;
double timePerTick = 1000000000l / targetTPS;
double timePerFrame = 1000000000l / targetFPS;
int maxFrameSkip = (int) ( (1000000000l / MINIMUM_FPS) / timePerTick);
int achievedPPS = 0;
int achievedFPS = 0;
int achievedTPS = 0;
long timer = TimeUtils.getMillis();
int loops = 0;
int achievedLoops = 0;
long currTime = 0l;
long loopTime = 0l;
long accumulatorPPS = 0l;
long accumulatorTPS = 0l;
long accumulatorFPS = 0l;
long lastTime = TimeUtils.getNano();
while(!isRequestedToStop) {
currTime = TimeUtils.getNano();
loopTime = currTime - lastTime;
lastTime = currTime;
loops = 0;
accumulatorPPS += loopTime;
accumulatorTPS += loopTime;
accumulatorFPS += loopTime;
if(accumulatorPPS >= timePerPoll) {
pollInputs();
playerLogic();
achievedPPS++;
accumulatorPPS -= timePerPoll;
}
while(accumulatorTPS >= timePerTick && loops < maxFrameSkip) {
tick();
achievedTPS++;
accumulatorTPS -= timePerTick;
loops++;
}
// Max 1 render per loop so player movement stays fluent
if(accumulatorFPS >= timePerFrame) {
render();
achievedFPS++;
accumulatorFPS -= timePerFrame;
}
if(TimeUtils.getDeltaMillis(timer) > 1000) {
timer += 1000;
logger.debug(achievedTPS + " TPS, " + achievedFPS + " FPS, "
+ achievedPPS + " Polls, " + achievedLoops + " Loops");
achievedTPS = 0;
achievedFPS = 0;
achievedLoops = 0;
}
achievedLoops++;
}
}
As you can see there is almost no code run on each loop but always a certain selection based on how much real time has passed. The question is referring to that 'worker loop' and how it does influence the system.