Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting frame rate with Thread.sleep()

Tags:

java

android

I am working on a live wallpaper, so no worries about physics collisions. I just want to have as smooth a frame rate as possible, up to a limit of 30fps to conserve battery.

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

However, I know that Thread.sleep() is not super accurate, and is likely to sleep longer than I ask for. I don't know by how much.

Is there a different method I can use that will provide a more even rate?

like image 307
Tenfour04 Avatar asked Aug 04 '11 13:08

Tenfour04


1 Answers

Yes, Thread.sleep() is not super-accurate.

You can try to use adaptive strategy -- do not just sleep(remaining), but have a variable long lastDelay, and, each time you observe too high frame rate you increase it, and Thread.sleep(lastDelay), each time you observe too low frame rate -- you decrease it. So after second or about your code find right number...

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

like image 128
BegemoT Avatar answered Oct 05 '22 05:10

BegemoT