Frame Rate Limit When Using Thread.sleep ()

I work on live wallpapers, so donโ€™t worry about collisions with physics. I just want to have as smooth a frame rate as possible, up to the limit of 30 frames per second, to save battery.

To do this, at the end of the cycle, and I measure the time from the beginning of this cycle. If the frame took less than 33 ms, I use Thread.sleep () for the sleeping number of ms to get up to 33.

However, I know that Thread.sleep () is not super accurate and will most likely sleep longer than I ask. I donโ€™t know how much.

Is it possible to use another method that will provide a more even speed?

+6
source share
3 answers

Yes, Thread.sleep () is not highly accurate.

You can try to use an adaptive strategy - not just to sleep (staying), but to have a variable long lastDelay, and each time you observe a too high frame rate, you increase it and Thread.sleep (lastDelay), each you observe a too low frame rate - you reduce it. So after the second or near your code, find the correct number ...

By the way, Thread.sleep is not the best way to limit the frame rate. Using a timer is more promising - but you will have the same problem since the accuracy of the timer is likely to be the same as Thread.sleep ()

+2
source

I'm not 100% sure, but you tried using a timer (http://developer.android.com/reference/java/util/Timer.html) and TimerTask (http: // developer. Android.com/reference/java/ util / TimerTask.html)? You should be able to use this to plan for updates.

+1
source

30 frames per second does not look smooth in a canvas animation. You should always try to save about 60 frames per second, and then adjust the speed of the sprites in accordance with the density of the screen. Thread.sleep () is accurate enough for wallpaper or 2nd game animation, you cannot see the difference if fps rises or falls only a few frames.

Or use the so-called frame-independent movement , where

deltaTime = timeNow - prevFrameTime; //for 60fps this should be ~0.016s object.x += speedX * deltaTime; 
0
source

Source: https://habr.com/ru/post/894288/


All Articles