可用异步装饰器捕获async函数执行时间,核心是用time.perf_counter()记录协程前后时间差并await原函数;它单调高精度、不受系统时钟影响,是官方推荐的计时方式;装饰器需支持任意参数透传与原样返回结果,保持类型透明和异常正常抛出。

可以用一个异步装饰器来捕获 async 函数的执行时间,核心是用 time.time() 或 time.perf_counter() 记录前后时间差,并在协程内部 await 原函数。
使用 perf_counter 获取高精度耗时
time.perf_counter() 比 time.time() 更适合测时:它单调、高精度、不受系统时钟调整影响,是 Python 官方推荐的性能计时方式。
- 在
async def装饰器内部,调用前记录起始时间 - await 原函数执行完毕后,立即记录结束时间
- 差值即为实际协程运行耗时(不含事件循环调度开销,但已足够反映逻辑耗时)
支持任意参数和返回值的通用写法
装饰器需用 *args, **kwargs 接收原 async 函数的所有入参,并将它们透传给被装饰函数;同时原样返回其结果,不破坏原有接口语义。
- 不能直接 return 原函数(它是 coroutine object),必须 await
- 返回值类型与原函数一致(比如返回
dict、int或None),保持类型透明 - 异常也会正常抛出,不影响错误传播
完整可运行示例
以下是一个简洁、健壮的 async 耗时装饰器:
import time
from functools import wraps
<p>def timing():
def decorator(func):
@wraps(func)
async def wrapper(*args, *<em>kwargs):
start = time.perf_counter()
result = await func(</em>args, **kwargs)
end = time.perf_counter()
print(f"{func.<strong>name</strong>} took {end - start:.4f}s")
return result
return wrapper
return decorator</p><h1>使用示例</h1><p>@timing()
async def fetch_data():
await asyncio.sleep(1.2)
return {"status": "done"}</p><h1>运行:asyncio.run(fetch_data())</h1>注意:装饰器本身返回的是闭包,所以要写成 @timing()(带括号调用),而非 @timing。这样能保持扩展性(比如后续加日志级别、阈值告警等参数)。
进阶建议:集成日志或结构化输出
生产环境中,建议把打印换成 logging.info,并补充函数名、参数摘要、耗时阈值判断等信息。
- 避免在 wrapper 中做耗时操作(如格式化长参数),可用
repr(args)[:50]截断 - 对超时函数可额外打 warning 级别日志,便于监控慢请求
- 若需统计分布(如 P95/P99),应配合 metrics 上报系统,而非仅打印











