Spread function calls evenly over time in Python
Question: Let's say i have a function in Python and it's pretty fast so i can call it in
a loop like 10000 times per second.

I'd like to call it, for example, 2000 times per second but with even
intervals between calls (not just call 2000 times and wait till the end of the
second). How can i achieve this in Python?


Answer: You can use the built-in
[`sched`](https://docs.python.org/2/library/sched.html) module which
implements a general purpose scheduler.

    
    
    import sched, time
    
    # Initialize the scheduler
    s = sched.scheduler(time.time, time.sleep)
    
    # Define some function for the scheduler to run
    def some_func():
        print('ran some_func')
    
    # Add events to the scheduler and run
    delay_time = 0.01
    for jj in range(20):
        s.enter(delay_time*jj, 1, some_func)
    s.run()
    

Using the `s.enter` method puts the events into the scheduler with a delay
relative to when the events are entered. It is also possible to schedule the
events to occur at a specific time with `s.enterabs`.

