python - 限制循环帧速率

标签 python

就像 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/

相关文章:

python - 需要解释 Python 中 json 和 dict 的区别

python - Lambda 函数更好还是迭代更好?

python - Django ModelForm 中的一个字段(ManyToMany)未保存到数据库

python - 有哪些 Kivy 教程可用

Python 没有从 subprocess.check_call 获取原始二进制文件

python - 将 numpy.random.get_state() 写入文件

python - 如何在 matplotlib 中定义多个图形对象?

python - Python 中的列表变得非常复杂

python - 配置 Django URLS.py 以在用 end/重写 URL 后将 #anchors 保留在 URL 中

python - 如何在 Python 的嵌套列表中获取具有最多共同元素的两个列表