Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

It would be better to base your "timing and math" on the amount of time actually passed since the last tick(). Depending on "very exact" timings will be fragile at the best of times.

Update: what I mean is that your tick() method would take an argument, say "t", of the elapsed time since the last call. Then, to do movement you'd store each thing's position (say in pixels) and velocity (in "pixels/second") so the magnitude of its movement for that call to tick() becomes "velocity * t".

This has the additional benefit of decoupling your physics simulation from the frame-rate.

I see pygame mentioned below: their "pygame.time.Clock.tick()" method is meant to be used this way, as it returns the number of seconds since the last time you called it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top