This code adjust itself for set FPS value. It is much more precise that time.sleep fps implementation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import time
_tick2_frame=0
_tick2_fps=20000000 # real raw FPS
_tick2_t0=time.time()
def tick(fps=60):
global _tick2_frame,_tick2_fps,_tick2_t0
n=_tick2_fps/fps
_tick2_frame+=n
while n>0: n-=1
if time.time()-_tick2_t0>1:
_tick2_t0=time.time()
_tick2_fps=_tick2_frame
_tick2_frame=0
#test:
while True:
tick(1) #1 frame per second
print _tick2_fps #see adjustment in action
|
I am woking on game in Tkinter and I've needed precise FPS implementation. This works fine :)
Let me share a few other implementations and ideas with you. The first is your code readied for Python 3, and the rest are self-correcting timing algorithms. They also provide errors when they cannot run the remaining code at the frames-per-second requested. My implementation of
tick
uses a callback to run the rest of the program, and theTimer
class is can be used similarly to how you wrote your code.Hi, Stephen. Thanks for your comment. I am sorry, but your code seems python3-only and uses not precise time.sleep. Can you provide more in-depth explanation, pls?
Jiri - the problem for most people is that your code seems to use a busy loop, which is not ideal for many applications as wastes CPU cycles - which is not great for a multi-tasking system.
True, Tony. But this code is made for a game, where it is not much of concern. I needed precision for high fps animations. This did the job.
Did you consider using a generator to maintain the last tick timestamp? I think you could generate how long to sleep and then use different sleep functions. time.sleep is in the standard library but others may use gevent.sleep.
I created a number of games in Free Python Games at http://www.grantjenks.com/docs/freegames/ but I didn't worry too much about high-precision FPS. I just put a plain sleep(50) or whatever call in the code. There's definitely room for improvement but the simplicity is hard to beat.