如何配置/基准化异步Python脚本(使用ASYNCIO)?
我通常会做
totalMem = tracemalloc.get_traced_memory()[0]
totalTime = time.time()
retValue = myFunction()
totalTime = time.time() - totalTime
totalMem = tracemalloc.get_traced_memory()[0] - totalMem
这样,我将节省该函数花费的总时间。 我学会了如何使用装饰器,并且做到了这一点-然后将所有统计信息转储到文本文件中以供以后分析。
但是,当您具有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]
现在,以某种方式,将其插入代码中:
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)
有没有一种方法可以完成此任务,而不必插入所有这些代码来分析我的所有异步代码? 还是已经有一个模块能够做到这一点?