如何用Python测量时间? [英] How to measure time in Python?

查看:122
本文介绍了如何用Python测量时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想启动我的程序,测量程序启动的时间,然后等待几秒钟,按一下按钮(K_RIGHT),然后按一下该按钮的时间。我正在使用Pygame来注册Keydown。但是在下面的代码中,它无法注册我的Keydown。我在这里做错了什么?

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 


推荐答案

下面是一个最小的完整示例,可以正确打印时间差异。通过的时间只是 time.time()(现在)与开始时间之间的差。

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.

您可以使用 pygame.time.get_ticks 而不是 time.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()

这篇关于如何用Python测量时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆