提问人:Wör Du Schnaffzig 提问时间:10/19/2020 最后编辑:Wör Du Schnaffzig 更新时间:10/19/2020 访问量:503
周期性功能执行,时间间隔< 100 ms
Periodic function execution with time interval < 100 ms
问:
我的目标是在周期性的时间间隔内执行一个函数,但周期很长。
下面链接的代码似乎很有前途:
https://medium.com/greedygame-engineering/an-elegant-way-to-run-periodic-tasks-in-python-61b7c477b679。
经过一些小的修改,我最终得到了这个:
import threading
import time
from datetime import timedelta
from unittest.mock import Mock
WAIT_TIME_SECONDS = 0.1
class PeriodicTask(threading.Thread):
""" Class for executing a periodic task specifying a time interval between invokations """
def __init__(self, interval: timedelta, execute: Callable[..., None], *args, **kwargs):
super().__init__()
assert isinstance(interval, timedelta), "Must specifiy datetime time interval, here"
assert not execute is None, "Must specify function which should be invoked regularly, here"
self.daemon = False
self.stopped = threading.Event()
self.interval = interval
self.execute = execute
self.args = args
self.kwargs = kwargs
def stop(self):
""" Stop periodic task """
self.stopped.set()
self.join()
def run(self):
""" Run task based on the specified interval """
while not self.stopped.wait(self.interval.total_seconds()):
self.execute(*self.args, **self.kwargs)
if __name__ == "__main__":
foo = Mock()
job = PeriodicTask(interval=timedelta(seconds=WAIT_TIME_SECONDS), execute=foo)
job.start()
time.sleep(1)
job.stop()
似乎我可以执行大约 100 毫秒的定期任务(Intel Core i7-3770K CPU,3.5 GHz,16 GB RAM),然后任务相互阻碍。有没有办法优化这个代码片段,这样我就可以定期执行任务,时间至少达到 10 毫秒?
答: 暂无答案
评论
print (f"Called function {foo.call_count} times.")
WAIT_TIME_SECONDS
call_count
WAIT_TIME_SECONDS
0.00001
90000
0.0000001