Skip to content Skip to sidebar Skip to footer

How To Measure Time In Python?

I want to start my program, measure the time when the program starts and then wait some seconds, push a button (K_RIGHT) and messure the time when I push the button. I am using Pyg

Solution 1:

Here's a minimal, complete example that prints the correct time difference. The passed time is just the difference between time.time() (now) and the start time.

You could use pygame.time.get_ticks instead of time.time as well (it returns the time in milliseconds instead of seconds).

import time
import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')

start = time.time()

done = False
whilenot done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_RIGHT:
                diff = time.time() - start
                print(diff)

    screen.fill(BG_COLOR)
    pg.display.flip()
    clock.tick(60)

pg.quit()

Post a Comment for "How To Measure Time In Python?"