ANSWER: The first loop is constantly rendering, even when update()
isn't being called, so unless you have other threads affecting variables other than the one calling update()
, it will render the same thing a few times until it's updated again. The main loop is running at max speed, which causes the higher CPU usage.
The second loop updates, renders, then sleeps for a bit, leaving the main thread completely idle. If other threads affect variables, you must wait until the the thread calling render()
is done sleeping and updating using update()
so render()
can finally render the new screen depending on how other threads affected it.
First loop is better if you are making a large-scale game consisting of multithreading, Second loop is better for games that only use one thread to run the entire game (so no delays between updating vars and rendering them, since one threaded games only update on one thread, and render triggers right after updating.
I've seen all kinds of different loops. my Question is what is the difference between these two loops: (all the reference vars arent needed, but are given for example)
long starttime = System.nanoTime();
int onesec = 1000000000;
int fps = 60;
double difference = 0;
double updatechecker;
while(true) {
long currenttime = System.nanoTime();
difference = (currenttime - starttime);
updatechecker = difference/(onesec/fps);
while(updatechecker >= 1) {
//update() here
updatechecker = 0;
}
//render() here
starttime = currenttime;
}
I understand that with more complicated loops like that, you can do things like seeing if theres time to render another screen before updating again and what not.
My question is whats the point of rendering faster than updating anyways? Why wouldn't something like this be more efficient:
while(running) {
long starttime = System.currentTimeMillis();
//update() here
//render() here
long endtime = System.currentTimeMillis();
try {
Thread.sleep((1000/60) + (starttime - endtime));
} catch(InterruptedException e) {
e.printStackTrace();
}
}
I know that with the first loop, you can do things like checking if theres time to render again before updating, but is there really a big difference between updating/rendering at the same and at different times? (you could also just use the first loop and put the render method where update is)
I found that using the Thread.sleep method drops my cpu usage by a ton. Im usually averaging 23-26% cpu with the first loop (rendering as fast as possible), and I average 2-4% cpu with the second loop. What's the better way to go? (pros and cons?)