Search code examples
javac++sleepframe-rate

16.66ms frames times. How do you get a perfect 60 fps when sleep() only goes by whole milliseconds?


I enjoy making little games in C++ and Java, but something has always bothered me, and I've never quite understood how to remedy it.

Sleep in C++ and Java only works in milliseconds. Meaning that if you do

startTime=clock();
-------Execute everything in that frame-----
endTime=clock(); 
sleep(x-(endTime-startTime));

if x is 16 you get 62.5 frames per second if x is 17 you get 58.8 frames per second

Neither of which is that perfect 60 to fit a monitor's refresh rate.

But I've noticed some games like Warframe will say "16.66 ms frame time" meaning that their engine was able to somehow sleep with greater precision.

So how do you get that perfect 60?

Preferably in C++ as that's what i'm working with right now, but answering for Java too would also be helpful


Solution

  • Relying on sleep alone is wrong anyway: you need scheduling at a fixed rate, and specified by you at the nanosecond precision. Use

    final ExecutorService scheduler = Executors.newScheduledThreadPool(1);
    scheduler.scheduleAtFixedRate(task, 0,
        TimeUnit.SECONDS.toNanos(1) / 60, 
        TimeUnit.NANOSECONDS);