简体   繁体   中英

Have python.sleep variate with computation time

For an animation project, we want to model a variable number of objects. This means that the computation and rendering part will take variable computation time. But we want the frame rate of the animation to remain constant. So we would like to compute how much time a section of code has taken, and if it is less then the expected frame rate, we wait the remainded before calculation the next frame.

Is there an easy way to do this?

One way to do it is by using the time library that has a method time that allows you to count how much time a section of code has taken to execute, an example down below.

import time
start_time = time.time()
#Your code here
end_time = time.time() - start_time
print(end_time)

You stopwatch the time, and sleep it for 1-x seconds.

sleep_time = 1/1 #Second number is frames per unit of time, first number is unit of time. In seconds.
from time import time #Important function: time(): Secs since unix epoch
while True: #Init animation
    init_time = time() #Init stopwatch
    #Code here Do your code
    timer = time()-init_time #End stopwatch and remember time in a variable.
    while time() < init_time+sleep_time-timer: pass #Wait ___ seconds
    #Restart and go to next frame.

If the code that you coded in lasts longer than 'sleep time', than it will not wait.

Hope this helps, and good luck with animating!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM