Original Post
Greetings, this is my very typical game loop (simplified):
while(running){
startOfLoop = System.currentTimeMillis();
gameLogic();
updateGraphics();
endOfLoop = System.currentTimeMillis();
loopTime = endOfLoop - startOfLoop;
while (loopTime < 50){
try { Thread.sleep(5); } catch (Exception e) {}
loopTime += 5;
}
}
As you can see, I'm aiming for 20fps. That's why the inner while-statement checks to see if the looptime is lower than 50ms. If it is, the threads sleeps for 5ms and 5ms are added to the counter, until it's over 50. After experimenting with different sleep values I found that using high values above 20 made the application eat upto 90% of total CPU cycles (I looked it up in the task manager). At 10, this slumped to about 30% and at 5 it's about 15%. I was wondering, why is it, that higher precision requires less CPU time? Is there a way to calculate an ideal value for sleep()? Or should you always use Thread.sleep(1)? I felt uncomfortable with that, thats why I left it at 5. What actually happens inside Thread.sleep()?