use*_*723 6 python benchmarking profiling python-asyncio
如何对异步 Python 脚本(使用 ASYNCIO)进行分析/基准测试?
我通常会做
totalMem = tracemalloc.get_traced_memory()[0]
totalTime = time.time()
retValue = myFunction()
totalTime = time.time() - totalTime
totalMem = tracemalloc.get_traced_memory()[0] - totalMem
Run Code Online (Sandbox Code Playgroud)
这样我就可以节省函数花费的总时间。我学会了如何使用装饰器,我就是这样做的 - 并将所有统计信息转储到文本文件中以供以后分析。
但是,当您拥有 ASYNCIO 脚本时,情况就大不相同了:该函数将在执行“await aiohttpSession.get()”时阻塞,并且控制将返回到事件循环,该循环将运行其他函数。
这样,经过的时间和总分配内存的变化不会显示任何内容,因为我将测量的不仅仅是该函数。
它会起作用的唯一方法是
class MyTracer:
def __init__(self):
self.totalTime = 0
self.totalMem = 0
self.startTime = time.time()
self.startMem = tracemalloc.get_traced_memory()[0]
def stop(self):
self.totalTime += time.time() - self.startTime
self.totalMem += tracemalloc.get_traced_memory()[0] - self.startMem
def start(self):
self.startTime = time.time()
self.startMem = tracemalloc.get_traced_memory()[0]
Run Code Online (Sandbox Code Playgroud)
现在,不知何故,将其插入代码中:
def myFunction():
tracer = MyTracer()
session = aiohttp.ClientSession()
# do something
tracer.stop()
# the time elapsed here, and the changes in the memory allocation, are not from the current function
retValue = await(await session.get('https://hoochie-mama.org/cosmo-kramer',
headers={
'User-Agent': 'YoYo Mama! v3.0',
'Cookies': 'those cookies are making me thirsty!',
})).text()
tracer.start()
# do more things
tracer.stop()
# now "tracer" has the info about total time spent in this function, and the memory allocated by it
# (the memory stats could be negative if the function releases more than allocates)
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点,我的意思是,在不必插入所有这些代码的情况下分析我所有的 asyncio 代码?或者是否有一个模块已经能够做到这一点?
小智 1
查看支持协程分析的Yappi 分析器。他们关于协程分析的页面非常清楚地描述了您面临的问题:
协程的主要问题是,当协程产生或换句话说上下文切换时,Yappi 会收到返回事件,就像我们退出函数一样。这意味着协程处于屈服状态时所花费的时间不会累积到输出中。这是一个问题,特别是对于挂机时间来说,因为在挂机时间中,您希望看到在该函数或协程中花费的全部时间。另一个问题是呼叫计数。您会看到每次协程产生时,调用计数都会增加,因为它是常规函数退出。
他们还非常高层次地描述了 Yappi 如何解决这个问题:
在 v1.2 中,Yappi 通过协程分析纠正了上述问题。在幕后,它区分了实际函数退出的收益率,如果选择挂墙时间作为时钟类型,它将累积时间并纠正调用计数指标。
| 归档时间: |
|
| 查看次数: |
779 次 |
| 最近记录: |