分析异步Python
介绍
应用程序分析是一个分析程序以确定其特征的过程:执行时间不同的代码零件和资源用法。
分析的主要阶段总是或多或少相同的:
- 测量执行时间。执行不同的代码零件需要多少时间?分析内存使用。程序的不同部分消耗了多少内存?识别瓶颈。代码的哪些部分减慢了程序或使用太多资源?>>性能优化。采取措施根据获得的数据提高执行速度和资源利用效率。有限数量的异步代码的特定瓶颈。让我们将每种类型与代码示例匹配。>
–
异步python中的瓶颈的主要类型
阻止操作
import asyncioimport timeasync def main(): print(‘start’) # blocking call time.sleep(3) # this blocks the entire event loop print(‘end’)asyncio.run(main())
顺序调用异步任务
import asyncioimport aiohttpasync def fetch(session, url): async with session.get(url) as response: return await response.text()async def main(): urls = ["medium."] * 10 async with aiohttp.clientsession() as session: # inefficient: sequential requests for url in urls:await fetch(session, url)asyncio.run(main())
过度上下文切换
import asyncioasync 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 asyncioasync 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 asyncioasync 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操作。>
内存开销
在这里,斯卡琳为我们做了一切,并立即向我们展示了有问题的代码。> –
结论
>应该注意的是,对于三种情况 – “
阻止操作”,“ 依次调用异步任务
>”和“> resource starvation
”相同的图片 – 系统%python%。澄清原因实际上需要开发人员。
如果您知道瓶颈的主要类型,并且准备仔细阅读profiler输出,那么python并不是一项艰巨且相当令人愉快的任务。
p.s.
这篇文章最初是在我一年多以前发布的。>
以上就是分析异步Python的详细内容,更多请关注范的资源库其它相关文章!
转载请注明:范的资源库 » 分析异步Python