性能分析器本质是接收函数并返回带计时能力新函数的高阶函数,使用time.perf_counter()精准计时,保持原函数签名不变,支持各类可调用对象及边界情况,并可扩展为返回耗时元组。

直接用高阶函数写一个性能分析器,本质就是写一个接收函数、返回新函数的包装逻辑。它不依赖任何框架或第三方库,核心在于“把计时行为塞进调用流程”,同时保持原函数签名和行为不变。
用 time.perf_counter() 获取高精度耗时
别用 time.time() —— 它受系统时间跳变影响,也不够准。真正适合性能分析的是 time.perf_counter():单调递增、纳秒级分辨率、专为测量短间隔设计。
- 调用前执行
start = time.perf_counter() - 调用后立即执行
elapsed = time.perf_counter() - start - 对毫秒级以下的函数(比如简单计算、字典查找)也能稳定捕获差异
封装成可复用的高阶函数
这个函数接收目标函数,返回一个带计时能力的新函数。不需要装饰器语法也能用,更贴近“高阶函数”本意:
import time
from functools import wraps
<p>def make_timer(func):
@wraps(func)
def timed_func(*args, *<em>kwargs):
start = time.perf_counter()
result = func(</em>args, **kwargs)
elapsed = time.perf_counter() - start
print(f"[{func.<strong>name</strong>}] 耗时 {elapsed:.6f} 秒")
return result
return timed_func
使用方式很直白:
fast_calc = make_timer(lambda x: x ** 2)-
fast_calc(123)→ 输出耗时并返回结果 - 也可用于已有函数:
process_data = make_timer(process_data)
支持业务函数类型全覆盖
只要函数可调用,就能套进去。包括:
- 普通函数(如数据清洗、字符串处理)
- 类中的实例方法(需先绑定,或改用
method_decorator变体) - 带默认参数、
*args、**kwargs的复杂接口 - 返回值为
None、生成器、异常等边界情况,都不影响计时逻辑
轻量扩展:返回耗时而不只是打印
如果业务需要把耗时传给监控系统或做阈值判断,可以微调返回结构:
def make_timer_with_result(func):
@wraps(func)
def timed_func(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
return result, elapsed # 返回元组:(结果, 耗时)
return timed_func
<h1>使用</h1><p>result, cost = make_timer_with_result(some_business_func)(input_data)
if cost > 0.5:
alert_slow_execution()


















