限制python中的Fps

时间:2011-12-05 17:04:06

标签: python timer frame-rate

我希望我的程序每隔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计数不准确?

2 个答案:

答案 0 :(得分:4)

如果要确定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评估处理睡眠电话。这是一个例子(应该忽略显示的循环#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回答。

答案 1 :(得分:0)

python documentation解释了为什么time.sleep不是很准确。

你正在使用什么操作系统?

如果您使用的是Linux,则可以使用powernap,它使用Linux的实时时钟(RTC)来实现更精确的计时。