I'm trying to write a python script where a line must be executed a defined number of times per second (corresponding to FPS). I'm having a precision problem that I guess comes from the time.time_ns() as it increases when I go into high tick per second values. If I put for example 240 ticks per second, my ticks per second counter will display 200 - 250 -250 -250 - 200. Impossible to have values between 200 and 250. Same thing, at lower values between 112 and 125 (I would have liked 120).
What is wrong with my logic, how can I improve it?
fps = 120
timeFrame_ns = 1000000000/fps
timeTickCounter = 0
count = 0
elapsedTime= time.time_ns()
while True:
if (time.time_ns() > timeTickCounter + 1000000000):
print("Ticks per second %s " % count)
if count != fps and count !=0:
diff = fps-count
ratio = diff/count
timeFrame_ns -= timeFrame_ns*ratio
timeTickCounter = time.time_ns()
count = 0
count += 1
while True:
if timeFrame_ns <= (time.time_ns()-elapsedTime):
break
elapsedTime= time.time_ns()
This script will print :
Ticks per second 0
Ticks per second 112
Ticks per second 125
Ticks per second 112
Ticks per second 125
Ticks per second 125
Ticks per second 112
Ticks per second 125
Ticks per second 125
Ticks per second 112
Ticks per second 125