This simple generator function is used to call a function X times per second.
1 2 3 4 5 6 7 8 9 10 11 12 13
def timed_call(callback, calls_per_second, *args, **kw): """ Create an iterator which will call a function a set number of times per second. """ time_time = time.time start = time_time() period = 1.0 / calls_per_second while True: if (time_time() - start) > period: start += period callback(*args, **kw) yield None
This iterator is useful for many things. I use it to control timed updates to objects in my games. It is especially useful for animating objects at a constant frame rate across systems with different processor speeds and video refresh rates.
You can call the iterator as often as possible in the main loop, and be assured that it will only run the callback function X times per second.