0

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?

pushist1y
  • 127
  • 1
  • 1
  • 6
  • Have you looked into Python's [sleep()](http://www.tutorialspoint.com/python/time_sleep.htm) method? You can call it before every function call. You'll just need to figure out a time (in milliseconds) that works best for your situation. – Xetnus Aug 23 '16 at 15:39
  • Depends where it is called. A naive way would be to call `time.sleep(1/2000)` but that isn't guaranteed to be 2000x/sec and could put your whole process to bed which may not be what you want. – Two-Bit Alchemist Aug 23 '16 at 15:39
  • Yes, i've looked into it but i've found this: http://stackoverflow.com/questions/1133857/how-accurate-is-pythons-time-sleep Looks like you can't rely on it for high frequencies/low delays – pushist1y Aug 23 '16 at 15:43

1 Answers1

0

You can use the built-in sched 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.

Chris Mueller
  • 6,490
  • 5
  • 29
  • 35