Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Pygame to registrate the Keydown. But in my code below it does not registrate my Keydown. What I am doing wrong here?

start = time.time()
for e in pygame.event.get():
    if e.type == pygame.KEYDOWN:
        if e.key == pygame.K_RIGHT:
           end= time.time()
           diff = end-start 
like image 308
ddd Avatar asked Nov 25 '25 08:11

ddd


1 Answers

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
while not 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()
like image 107
skrx Avatar answered Nov 26 '25 22:11

skrx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!