python 测时间,如何用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

解决方案

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值