我正在使用python3编写应用程序,并且我是第一次尝试使用asyncio。我遇到的一个问题是我的一些协程阻止事件循环的时间比我想要的长。我试图在事件循环的顶部找到一些东西,它将显示运行每个协同程序所花费的壁/ CPU时间。如果没有任何已经存在的东西,是否有人知道如何将钩子添加到事件循环中以便我可以进行测量?
我尝试过使用cProfile,它提供了一些有用的输出,但我对阻塞事件循环的时间更感兴趣,而不是总执行时间。
答案 0 :(得分:11)
事件循环已经可以跟踪协同程序是否需要很多CPU时间来执行。要查看它,您应enable debug mode使用set_debug
方法:
import asyncio
import time
async def main():
time.sleep(1) # Block event loop
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.set_debug(True) # Enable debug
loop.run_until_complete(main())
在输出中你会看到:
Executing <Task finished coro=<main() [...]> took 1.016 seconds
默认情况下,它会显示阻止超过0.1秒的协同程序的警告。它没有记录,但基于asyncio source code,看起来您可以更改slow_callback_duration
属性来修改此值。
答案 1 :(得分:6)
您可以使用call_later
。定期运行回调,记录/通知循环的时间和周期间隔时间的差异。
class EventLoopDelayMonitor:
def __init__(self, loop=None, start=True, interval=1, logger=None):
self._interval = interval
self._log = logger or logging.getLogger(__name__)
self._loop = loop or asyncio.get_event_loop()
if start:
self.start()
def run(self):
self._loop.call_later(self._interval, self._handler, self._loop.time())
def _handler(self, start_time):
latency = (self._loop.time() - start_time) - self._interval
self._log.error('EventLoop delay %.4f', latency)
if not self.is_stopped():
self.run()
def is_stopped(self):
return self._stopped
def start(self):
self._stopped = False
self.run()
def stop(self):
self._stopped = True
例如
import time
async def main():
EventLoopDelayMonitor(interval=1)
await asyncio.sleep(1)
time.sleep(2)
await asyncio.sleep(1)
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
输出
EventLoop delay 0.0013
EventLoop delay 1.0026
EventLoop delay 0.0014
EventLoop delay 0.0015
答案 2 :(得分:0)
要在其中一个答案上展开一点,如果你想监控你的循环和检测挂起,那么这里就是一个片段。它启动一个单独的线程,检查循环的任务是否最近产生了执行。
def monitor_loop(loop, delay_handler):
loop = loop
last_call = loop.time()
INTERVAL = .5 # How often to poll the loop and check the current delay.
def run_last_call_updater():
loop.call_later(INTERVAL, last_call_updater)
def last_call_updater():
nonlocal last_call
last_call = loop.time()
run_last_call_updater()
run_last_call_updater()
def last_call_checker():
threading.Timer(INTERVAL / 2, last_call_checker).start()
if loop.time() - last_call > INTERVAL:
delay_handler(loop.time() - last_call)
threading.Thread(target=last_call_checker).start()
答案 3 :(得分:0)