我目前在大学读物理,我学习 python 作为一个小爱好。

为了同时练习两者,我想我会写一个小“物理引擎”,它根据 x、y 和 z 坐标计算对象的运动。我只会以文本形式返回运动(至少现在是这样!)但我希望位置更新是实时的。

为此,我需要更新对象的位置,例如每秒一百次,然后将其打印回屏幕。因此,程序每 10 毫秒打印一次当前位置。

因此,如果计算的执行需要 2 毫秒,那么循环必须等待 8 毫秒才能打印并重新计算下一个位置。

构建这样的循环的最佳方法是什么,每秒 100 次是一个合理的频率,或者你会慢一点,比如 25 次/秒?

最佳答案

在 python 中等待的基本方法是 import time 并使用 time.sleep 。那么问题来了,睡多久?这取决于您希望如何处理循环错过所需时间的情况。如果未命中,以下实现会 try catch 目标间隔。

import time
import random

def doTimeConsumingStep(N):
    """
    This represents the computational part of your simulation.

    For the sake of illustration, I've set it up so that it takes a random
    amount of time which is occasionally longer than the interval you want.
    """
    r = random.random()
    computationTime = N * (r + 0.2)
    print("...computing for %f seconds..."%(computationTime,))
    time.sleep(computationTime)


def timerTest(N=1):
    repsCompleted = 0
    beginningOfTime = time.clock()

    start = time.clock()
    goAgainAt = start + N
    while 1:
        print("Loop #%d at time %f"%(repsCompleted, time.clock() - beginningOfTime))
        repsCompleted += 1
        doTimeConsumingStep(N)
        #If we missed our interval, iterate immediately and increment the target time
        if time.clock() > goAgainAt:
            print("Oops, missed an iteration")
            goAgainAt += N
            continue
        #Otherwise, wait for next interval
        timeToSleep = goAgainAt - time.clock()
        goAgainAt += N
        time.sleep(timeToSleep)

if __name__ == "__main__":
    timerTest()

请注意,在普通操作系统上,您将错过所需的时间,因此此类操作是必要的。请注意,即使使用像 tulip 和 twisted 这样的异步框架,您也无法保证在正常操作系统上的计时。

关于python - 控制循环速度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23252796/

10-11 22:36
查看更多