【问题标题】:How to measure time in Python?如何在 Python 中测量时间?
【发布时间】:2019-05-17 01:57:09
【问题描述】:

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

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.sleep(),但那是错误的。
  • 尝试使用 pygame 内置时间模块而不是使用时间模块,即。 pygame.time.clock() 等价于 time.time()。尝试使用 pygame 内置函数。
  • 感谢您的提示,但如果函数是等价的,会有什么不同吗?
  • @ddd 功能级别不多,编码级别太多(更多pythonic方式)但是您使用pygame作为核心组件,那么通常的做法是尽可能多地使用该包内置功能。更干净的代码。

标签: python datetime time pygame


【解决方案1】:

这是一个打印正确时差的最小完整示例。经过的时间只是time.time()(现在)和开始时间之间的差。

您也可以使用pygame.time.get_ticks 代替time.time(它以毫秒而不是秒返回时间)。

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

【讨论】:

  • 哇,它有效!我想问你:在这种情况下你使用 time.clock() 做什么?而在使用“while not done”循环时?这种情况下需要吗?
  • pygame.time.Clock 用于限制帧率,否则程序将尽可能快地运行。 clock.tick(60) 在这种情况下将其限制为每秒 60 帧。 -- 是的,while 循环是必要的。
  • 为什么?如果我理解正确,它只看 Pygame 是否打开?而且 pg.display.flip() 也不是真的需要,我是对的吗?
  • 如果没有循环,程序将立即完成,窗口将关闭。 -- 是的,如果你不想画任何东西,你可以删除pg.display.flip()screen.fill(BG_COLOR)
猜你喜欢
  • 2019-12-30
  • 2023-02-26
  • 1970-01-01
  • 2013-01-05
  • 2011-04-03
相关资源
最近更新 更多