i want my program to do a task every x frames. However it does not seem to work, due to the fact that the timer in python seems to be inaccurate. How do i get this piece of code to obey my set framerate?
import time
fps = 5
skipticks = 1/(fps*1.0)
i= 0
nextsnap=time.clock()
print skipticks, fps
while (True):
tim= time.clock()
i=i+1
# this prints the fps
#'print 'Fps at start',i, 1/(time.time()-tim)
# this is the sleep that limits the fps
nextsnap+=skipticks
sleeptime = nextsnap-time.clock()
if (sleeptime>0):
time.sleep (sleeptime)
else:
print 'took too long'
print 'Fps at end:#', i, 1/(time.clock()-tim)
this produces on my computer:
Fps at end:# 45 4.36627853079
Fps at end:# 46 6.44119324776
Fps at end:# 47 4.53966049676
Fps at end:# 48 4.66471670624
Fps at end:# 49 7.18312473536
Fps at end:# 50 4.34786490268
Fps at end:# 51 6.5263951487
Fps at end:# 52 4.71715853908
Fps at end:# 53 4.59636712435
Fps at end:# 54 6.87201830723
Fps at end:# 55 4.31062740848
Why are there frames that are rendered too fast? And why is the fps count inaccurate?