问题
I have a counter working that counts every frame. what I want to do is divide this by time to determine the FPS of my program. But I'm not sure how to perform operations on timing functions within python.
I've tried initializing time as
fps_time = time.time
fps_time = float(time.time)
fps_time = np.float(time.time)
fps_time = time()
Then for calculating the fps,
FPS = (counter / fps_time)
FPS = float(counter / fps_time)
FPS = float(counter (fps_time))
But errors I'm getting are object is not callable or unsupported operand for /: 'int' and 'buildin functions'
thanks in advance for the help!
回答1:
Here is a very simple way to print your program's frame rate at each frame (no counter needed) :
import time while True: start_time = time.time() # start time of the loop ######################## # your fancy code here # ######################## print("FPS: ", 1.0 / (time.time() - start_time)) # FPS = 1 / time to process loop
If you want the average frame rate over x seconds, you can do like so (counter needed) :
import time start_time = time.time() x = 1 # displays the frame rate every 1 second counter = 0 while True: ######################## # your fancy code here # ######################## counter+=1 if (time.time() - start_time) > x : print("FPS: ", counter / (time.time() - start_time)) counter = 0 start_time = time.time()
Hope it helps!
回答2:
Works like a charm
import time
import collections
class FPS:
def __init__(self,avarageof=50):
self.frametimestamps = collections.deque(maxlen=avarageof)
def __call__(self):
self.frametimestamps.append(time.time())
if(len(self.frametimestamps) > 1):
return len(self.frametimestamps)/(self.frametimestamps[-1]-self.frametimestamps[0])
else:
return 0.0
fps = FPS()
for i in range(100):
time.sleep(0.1)
print(fps())
Make sure fps is called once per frame
回答3:
You might want to do something in this taste:
def program():
start_time = time.time() #record start time of program
frame_counter = 0
# random logic
for i in range(0, 100):
for j in range(0, 100):
# do stuff that renders a new frame
frame_counter += 1 # count frame
end_time = time.time() #record end time of program
fps = frame_counter / float(end_time - start_time)
Of course you don't have to wait the end of the program to compute end_time and fps, you can do it every now and then to report the FPS as the program runs. Re-initing start_time after reporting the current FPS estimation could also help with reporting a more precise FPS estimation.
来源:https://stackoverflow.com/questions/43761004/fps-how-to-divide-count-by-time-function-to-determine-fps