Python - time.sleep () offset by code duration

I have a function that runs tick () for all players and objects on my game server. I do this by looping through the set every 0.1 seconds. I need it to be durable. A lot of time and math depends on this pause, the maximum possible up to 0.1 seconds. For this, I added this to the tick tag:

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 cycle is 0.01, then time_lapsed == 0.01 ... and then sleep should only be 0.09. I ask because it does not seem to work. The other day, I started to get an overloaded message on the server, and the server was definitely not overloaded. Any thoughts on a good way to dynamically control sleep? Maybe there is another way to run the code every tenth of a second without sleep?

+8
python time mud
source share
2 answers

Other Python threads can be run in between to leave the thread less time. In addition, time.time() regulated by the system time; It can be installed back.

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

To avoid external influences, you can save an independent frame / step counter for measuring game time.

+2
source share

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

Update: I mean that your tick () method will take an argument, like "t", elapsed time since the last call. Then, in order to make a movement, you must store each item’s position (say, in pixels) and speed (in “pixels / seconds”), so its magnitude for this tick () call becomes “speed * t”.

This has the added benefit of decoupling your physical simulation with frame rate.

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

+3
source share

All Articles