应用程序分析是一个分析程序以确定其特征的过程:执行时间不同的代码零件和资源用法。
异步python中的瓶颈的主要类型
阻止操作
import asyncio import time async def main(): print('start') # blocking call time.sleep(3) # this blocks the entire event loop print('end') asyncio.run(main())
import asyncio import aiohttp async def fetch(session, url): async with session.get(url) as response: return await response.text() async def main(): urls = ["http://medium.com"] * 10 async with aiohttp.clientsession() as session: # inefficient: sequential requests for url in urls: await fetch(session, url) asyncio.run(main())
import asyncio async def tiny_task(): await asyncio.sleep(0.0001) async def main(): # excessive context switching due to many small tasks await asyncio.gather(*(tiny_task() for _ in range(100000))) asyncio.run(main())
import asyncio async def long_running_task(): await asyncio.sleep(10) print("long task executed") async def quick_task(): await asyncio.sleep(1) print("quick task executed") async def main(): await asyncio.gather( long_running_task(), quick_task() # may be delayed excessively ) asyncio.run(main())
import asyncio async def large_data_task(): data = "lorep ipsum" * 10**8 # large memory usage await asyncio.sleep(1) async def main(): tasks = [large_data_task() for _ in range(100)] # high memory consumption await asyncio.gather(*tasks) asyncio.run(main())
>确定性剖析师
。主要代表是内置的cprofile。该探测器计算每个函数的调用数量以及功能所花费的时间。问题在于,异步呼叫的等待时间没有考虑到。统计剖面。普通代表是鳞状,py-spy,yappi,pyinsprument,奥斯汀。这样的探索者以某种频率进行了该过程的“快照”,并应用了统计分析的方法来搜索瓶颈。
-为什么要鳞?因为此工具允许分析cpu和内存,因此在github上具有10k 星星,并且该项目正在积极开发。 >让我们看看上面列表中每个“有问题”代码的scalene所说的。
>36277728875
阻止操作
>您可以立即看到问题线,并立即阻止呼叫 - python的2%,在系统呼叫中的98%的时间。
顺序调用异步任务
>这里有点复杂。您可以看到90%的时间用于系统调用,但是该行已更改 - 现在它是
过度上下文切换
>
资源饥饿
再次,系统与python的时间比不支持python操作。
>应该注意的是,对于三种情况 - “ 立即学习“Python免费学习笔记(深入)”; >”和“
如果您知道瓶颈的主要类型,并且准备仔细阅读profiler输出,那么python并不是一项艰巨且相当令人愉快的任务。
我们看到内存消耗如何在
>
在这里,斯卡琳为我们做了一切,并立即向我们展示了有问题的代码。
-
结论
”,“
依次调用异步任务> resource starvation
>
以上就是分析异步Python的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号