gpt4 book ai didi

python - 限制循环帧速率

转载 作者:行者123 更新时间:2023-12-01 05:02:37 25 4
gpt4 key购买 nike

就像 pygame我想限制循环的帧速率。 Pygame 提供了 pygame.time.Clock.tick() 方法来做到这一点:

If you pass the optional framerate argument the function will delay to keep the game running slower than the given ticks per second. This can be used to help limit the runtime speed of a game. By calling Clock.tick(40) once per frame, the program will never run at more than 40 frames per second.

但是如何在 python 中本地实现呢?

举例说明:

import time

max_frames = 125 # 25*5
current_frame = 1
while current_frame <= max_frames:
print('frame', time.clock(), current_frame)
current_frame += 1

生产:

('frame', 0.01, 1)
('frame', 0.01, 2)
('frame', 0.01, 3)
[...]
('frame', 0.01, 124)
('frame', 0.01, 125)

我想要每秒 25 帧,所以

('frame', 0.01, 1)
('frame', 0.05, 2)
('frame', 0.08, 3)
[...]
('frame', 4.98, 124)
('frame', 5.00, 125)

最佳答案

您可以使用 time.sleep(1./25) 等待 1/25 秒。

while current_frame <= max_frames:
# ... do stuff
time.sleep(1./25)

请注意,无论循环体花费什么时间,都会另外等待该时间。或者,记住上次执行时间并等待这次 + 1/25 秒。

while current_frame <= max_frames:
start = time.time()
# ... do stuff that might take significant time
time.sleep(max(1./25 - (time.time() - start), 0))

关于python - 限制循环帧速率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25743450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com