Spread function calls evenly over time in Python

时间:2016-08-23 15:36:05

标签: python

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?

1 个答案:

答案 0 :(得分:0)

您可以使用内置的sched模块来实现通用调度程序。

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()

使用s.enter方法将事件放入调度程序,相对于输入事件的时间延迟。也可以使用s.enterabs安排事件在特定时间发生。