在python中记录异步函数的执行时间

Jac*_*eng 2 python async-await

我有一个异步函数,例如a。它被用作b = await a()

我如何记录a()完成执行所需的时间?

And*_*ely 6

您可以使用time.monotonic()

例如:

import asyncio
import time


async def a():
    await asyncio.sleep(3)
    return 1

async def main():
    start_time = time.monotonic()

    b = await a()

    print('time: ', time.monotonic() - start_time)

asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)

印刷:

time:  3.002365263993852
Run Code Online (Sandbox Code Playgroud)