Search code examples
pythonpygameframe-rate

Show FPS in Pygame


I'm working on a project with my friend in python with pygame. We have tried to make an FPS counter in our game but we haven't succeeded. The FPS counter is always displaying a zero. Here is the code:

#Create Text
def Render_Text(what, color, where):
    font = pygame.font.Font('assets/Roboto.ttf', 30)
    text = font.render(what, 1, pygame.Color(color))
    window.blit(text, where)
#Show FPS
    Render_Text(str(int(clock.get_fps())), (255,0,0), (0,0))
    print("FPS:", int(clock.get_fps()))

Solution

  • get_fps() only gives a correct result, when you call tick() once per frame:

    clock = pygame.time.Clock()
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False          
    
        clock.tick()
        print(clock.get_fps())
    
        # [...]
    

    See the documentation of get_fps()

    get_fps() compute the clock framerate

    get_fps() -> float

    Compute your game's framerate (in frames per second). It is computed by averaging the last ten calls to Clock.tick().