Search code examples
pythontimemud

Python -- time.sleep() offset by code duration


I have a function that runs a tick() for all players and objects within my game server. I do this by looping through a set every .1 seconds. I need it to be a solid .1. Lots of timing and math depends on this pause being as exact as possible to .1 seconds. To achieve this, I added this to the tick thread:

start_time = time.time()

# loops and code and stuff for tick thread in here...

time_lapsed = time.time() - start_time # get the time it took to run the above code
if 0.1 - time_lapsed > 0:
    time.sleep(0.1 - time_lapsed)
else:
    print "Server is overloaded!"
    # server lag is greater that .1, so don't sleep, and just eat it on this run. 
    # the goal is to never see this.

My question is, is this the best way to do this? If the duration of my loop is 0.01, then time_lapsed == 0.01 ... and then the sleep should only be for 0.09. I ask, because it doesn't seem to be working. I started getting the overloaded server message the other day, and the server was most definitely not overloaded. Any thoughts on a good way to "dynamically" control the sleep? Maybe there's a different way to run code every tenth of a second without sleeping?


Solution

  • Other Python threads may run in between leaving your thread less time. Also time.time() is subject to system time adjustments; it can be set back.

    There is a similar function Clock.tick() in pygame. Its purpose is to limit the maximum frame rate.

    To avoid outside influence you could keep an independent frame/turn-based counter to measure the game time.