fps - how to divide count by time function to determine fps

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


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.


  • 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!