I wonder if this gameloop in Java is accurate to give around 60 frames a second, is it?

public void run() {
    long then = System.nanoTime();
    long targetFPS = 60;
    Timer timer = new Timer();

        long now = System.nanoTime();
        long updateLength = now - then;
        long update = updateLength / targetFPS;
        then = now;
        if(update >= 16){
  • 1
    \$\begingroup\$ Measure it (filler) \$\endgroup\$ – Bálint Apr 25 '17 at 11:35
  • 1
    \$\begingroup\$ Also do you not generally tick then render? \$\endgroup\$ – lozzajp Apr 25 '17 at 11:42

It isn't.

This keeps the CPU running constantly, which uses a lot of power. Also, system.nanotime can be really slow on certain PCs. Instead try something like:

long time = System.currentTimeMillis();
// Do your stuff
Thread.sleep(Math.max(0, time - 16));

This doesn't exactly produce 60 fps, because that requires 16,66 milliseconds between frames, but it's really close.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.