监控 asyncio 事件循环 [英] Monitoring the asyncio event loop

查看:41
本文介绍了监控 asyncio 事件循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python3 编写一个应用程序,并且我是第一次尝试 asyncio.我遇到的一个问题是我的一些协程阻塞事件循环的时间比我喜欢的要长.我正在尝试为事件循环找到一些与 top 相关的东西,它将显示运行我的每个协程花费了多少墙/cpu 时间.如果没有任何现有的东西,有没有人知道一种向事件循环添加钩子以便我可以进行测量的方法?

I am writing an application using python3 and am trying out asyncio for the first time. One issue I have encountered is that some of my coroutines block the event loop for longer than I like. I am trying to find something along the lines of top for the event loop that will show how much wall/cpu time is being spent running each of my coroutines. If there isn't anything already existing does anyone know of a way to add hooks to the event loop so that I can take measurements?

我尝试使用 cProfile,它提供了一些有用的输出,但我更感兴趣的是阻塞事件循环所花费的时间,而不是总执行时间.

I have tried using cProfile which gives some helpful output, but I am more interested in time spent blocking the event loop, rather than total execution time.

推荐答案

事件循环已经可以跟踪协程是否需要大量 CPU 时间来执行.要查看它,您应该启用调试模式set_debug 方法:

Event loop can already track if coroutines take much CPU time to execute. To see it you should enable debug mode with set_debug method:

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 源代码,看起来您可以更改 slow_callback_duration 属性来修改此值.

By default it shows warnings for coroutines that blocks for more than 0.1 sec. It's not documented, but based on asyncio source code, looks like you can change slow_callback_duration attribute to modify this value.

这篇关于监控 asyncio 事件循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆