gpt4 book ai didi

python - 在 python 中限制 Fps

转载 作者:太空宇宙 更新时间:2023-11-04 10:57:50 27 4
gpt4 key购买 nike

我希望我的程序每 x 帧执行一次任务。但是它似乎不起作用,因为 python 中的计时器似乎不准确。我如何让这段代码服从我设置的帧率?

import time
fps = 5
skipticks = 1/(fps*1.0)
i= 0
nextsnap=time.clock()
print skipticks, fps
while (True):
tim= time.clock()
i=i+1
# this prints the fps
#'print 'Fps at start',i, 1/(time.time()-tim)
# this is the sleep that limits the fps
nextsnap+=skipticks
sleeptime = nextsnap-time.clock()
if (sleeptime>0):
time.sleep (sleeptime)
else:
print 'took too long'
print 'Fps at end:#', i, 1/(time.clock()-tim)

这在我的电脑上产生:

 Fps at end:# 45 4.36627853079
Fps at end:# 46 6.44119324776
Fps at end:# 47 4.53966049676
Fps at end:# 48 4.66471670624
Fps at end:# 49 7.18312473536
Fps at end:# 50 4.34786490268
Fps at end:# 51 6.5263951487
Fps at end:# 52 4.71715853908
Fps at end:# 53 4.59636712435
Fps at end:# 54 6.87201830723
Fps at end:# 55 4.31062740848

为什么有些帧渲染的太快了?为什么 fps 计数不准确?

最佳答案

如果是关于测量 time.clock()time.sleep() 的准确性,请使用尽可能简单的方法,例如:

import time

fps = 5
time_delta = 1./fps

while True:
t0 = time.clock()
time.sleep(time_delta)
t1 = time.clock()
print 1. / (t1 - t0)

您的操作系统是什么?这个简单措施的结果是什么?

如果是关于清理您的代码,我会更清楚地分开FPS 评估处理 sleep 调用。这是一个示例(应忽略显示的循环 #0 频率)。

import time
import random
from itertools import count

fps = 5
loop_delta = 1./fps

current_time = target_time = time.clock()
for i in count():
#### loop frequency evaluation
previous_time, current_time = current_time, time.clock()
time_delta = current_time - previous_time
print 'loop #%d frequency: %s' % (i, 1. / time_delta)

#### processing
# processing example that sleeps a random time between 0 and loop_delta/2.
time.sleep(random.uniform(0, loop_delta / 2.))

#### sleep management
target_time += loop_delta
sleep_time = target_time - time.clock()
if sleep_time > 0:
time.sleep(sleep_time)
else:
print 'took too long'

此外,您可能需要 time.time() 而不是 time.clock()。参见 time.clock() vs. time.time() - accuracy回答。

关于python - 在 python 中限制 Fps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8388967/

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