Python 限制循环帧速率

Python 限制循环帧速率,python,Python,就像我想限制循环的帧速率一样。Pygame提供了Pygame.time.Clock.tick()方法: 如果您传递可选的framerate参数,函数将延迟以使游戏运行速度低于给定的每秒滴答数。这可以用来帮助限制游戏的运行速度。通过每帧调用Clock.tick(40)一次,程序的运行速度将永远不会超过每秒40帧 但是如何在python中以本机方式实现呢 举例说明: import time max_frames = 125 # 25*5 current_frame = 1 while curren

就像我想限制循环的帧速率一样。Pygame提供了Pygame.time.Clock.tick()方法:

如果您传递可选的framerate参数,函数将延迟以使游戏运行速度低于给定的每秒滴答数。这可以用来帮助限制游戏的运行速度。通过每帧调用Clock.tick(40)一次,程序的运行速度将永远不会超过每秒40帧

但是如何在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
我希望每秒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)
while current_frame <= max_frames:
    start = time.time()
    # ... do stuff that might take significant time
    time.sleep(max(1./25 - (time.time() - start), 0))

当当前帧时,您可以使用
time.sleep(1./25)
等待1/25秒

while current_frame <= max_frames:
    # ... do stuff 
    time.sleep(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))
而current_frame假设“本机使用python”是指使用python标准库,模块确实提供了足够的构建块,但很可能不是您想要的。其核心是,帧速率限制只是等待适当的时间:

from time import time, sleep

fps=5
frameperiod=1.0/fps
now=time()
nextframe=now+frameperiod
for frame in range(120):
  print frame, now
  while now<nextframe:
    sleep(nextframe-now)
    now=time()
  nextframe+=frameperiod
从时间导入时间,睡眠
fps=5
帧周期=1.0/fps
现在=时间()
下一帧=现在+帧周期
对于范围内的帧(120):
现在打印相框
现在假设“本机使用python”是指使用python标准库,模块确实提供了足够的构建块,但它很可能不是您想要的。其核心是,帧速率限制只是等待适当的时间:

from time import time, sleep

fps=5
frameperiod=1.0/fps
now=time()
nextframe=now+frameperiod
for frame in range(120):
  print frame, now
  while now<nextframe:
    sleep(nextframe-now)
    now=time()
  nextframe+=frameperiod
从时间导入时间,睡眠
fps=5
帧周期=1.0/fps
现在=时间()
下一帧=现在+帧周期
对于范围内的帧(120):
现在打印相框

而现在好办法谢谢了!我刚刚读到了什么时候.clock()被弃用,因为python 3.3真是太好了,谢谢!我刚刚读到了自python 3.3以来,time.clock()被弃用的时间