直接套用@timeit报错是因为带参装饰器必须三层嵌套:timer(接收参数)→ decorator(接收函数)→ wrapper(执行逻辑),缺一层就会导致参数传递错误。

为什么直接套用 @timeit 会报错:missing 1 required positional argument
常见错误是把装饰器写成普通函数形式,比如:
def timeit(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.time() - start:.3f}s")
return result
return wrapper
这样写没问题,但一旦你想加参数(比如控制是否打印、设置阈值告警),@timeit(threshold=0.1) 就会失败——Python 解释器会直接把 threshold=0.1 当作被装饰函数传给 timeit,而不是传给外层闭包。
根本原因是:带参装饰器必须是「返回装饰器的函数」,共三层嵌套。
正确结构:三层函数,每层职责分明
必须拆成:timer(接收装饰器参数)→ 返回 decorator(接收被装饰函数)→ 返回 wrapper(执行逻辑)。缺一层都会出错。
立即学习“Python免费学习笔记(深入)”;
-
timer:只处理装饰器自身的配置,如threshold、verbose -
decorator:只接收func,不能碰任何装饰器参数(它们在上层闭包里) -
wrapper:只负责运行时逻辑,调用func并测时
示例:
import time
from functools import wraps
<p>def timer(threshold=0.0, verbose=True):
def decorator(func):
@wraps(func) # 防止丢失 <strong>name</strong> 和 docstring
def wrapper(*args, *<em>kwargs):
start = time.perf_counter()
result = func(</em>args, **kwargs)
elapsed = time.perf_counter() - start
if verbose:
if elapsed > threshold:
print(f"[ALERT] {func.<strong>name</strong>} took {elapsed:.4f}s (>{threshold}s)")
else:
print(f"{func.<strong>name</strong>} took {elapsed:.4f}s")
return result
return wrapper
return decorator
使用时注意 @timer() 和 @timer 的区别
这是最容易混淆的点。Python 要求带参装饰器**必须加括号调用**,哪怕没传参数:
-
@timer→ 错!这等价于timer(func),但timer期望先收threshold,会报TypeError: timer() missing 1 required positional argument -
@timer()→ 对!相当于timer()(func),先调用timer得到decorator,再把它应用到func -
@timer(threshold=0.5)→ 对!参数传给最外层timer
如果想支持无括号写法(即兼容 @timer 和 @timer()),得额外判断参数类型,反而增加歧义和维护成本,不推荐。
性能与兼容性:别用 time.time(),优先选 time.perf_counter()
time.time() 返回的是系统时间戳,受系统时钟调整(NTP 同步、手动改时间)影响,测短耗时不准甚至为负;而 time.perf_counter() 是单调递增的高精度计时器,专为性能测量设计。
另外两个细节常被忽略:
- 务必用
@wraps(func)包装wrapper,否则被装饰函数的__name__变成wrapper,调试、日志、框架反射(如 FastAPI 依赖注入)都会出问题 - 如果函数可能抛异常,记得在
wrapper中用try/finally或捕获后重新抛出,否则异常发生时耗时不记录,还可能掩盖真实错误位置
真正上线用的耗时监控,往往还要考虑线程安全(避免共享变量)、异步函数支持(async def)、以及采样率控制(不是每个调用都打日志)——这些都不是加个 @timer() 就能解决的。


















