限制python中的Fps [英] Limiting Fps in python

查看:211
本文介绍了限制python中的Fps的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的程序每x帧执行一次任务.但是,由于python中的计时器似乎不准确,因此它似乎不起作用.如何获得这段代码来遵守我设定的帧率?

i want my program to do a task every x frames. However it does not seem to work, due to the fact that the timer in python seems to be inaccurate. How do i get this piece of code to obey my set framerate?

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)

这在我的计算机上产生:

this produces on my computer:

 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计数不正确?

Why are there frames that are rendered too fast? And why is the fps count inaccurate?

推荐答案

如果要确保您使用time.clock()time.sleep()可以达到的准确性,请使用尽可能简单的方法,例如:

If it's about mesuring the accuracy you can have with time.clock() and time.sleep(), use something as simple as possible like:

import time

fps = 5
time_delta = 1./fps

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

您的操作系统是什么,这种简单的测量结果是什么?

What is your OS and what is the result of this simple mesure ?

如果要清理代码,我会更清楚地区分 FPS评估处理休眠呼叫.这是一个示例(显示的回路#0频率应忽略).

If it's about cleaning your code, I would separate more clearly the FPS evaluation, the processing and the sleep call. Here is an example (the loop #0 frequency displayed should be ignored).

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()与time.time()-准确性答案.

Also, you probably want time.time() rather than time.clock(). See time.clock() vs. time.time() - accuracy answer.

这篇关于限制python中的Fps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆