python 装饰器记录函数用时

装饰器

py 复制代码
# 用于记录函数平均用时的装饰器
def average_time_decorator(func):
    times = []

    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        t = end_time - start_time
        times.append(t)  # 记录用时
        print(f"{func.__name__} 的用时: {t:.6f} 秒")
        return result

    def get_avg_time():
        avg_time = sum(times)/len(times) if len(times) > 0 else 0.
        return avg_time
    
    def clear_cache():
        nonlocal times
        times = []

    wrapper.get_avg_time = get_avg_time
    wrapper.clear_cache = clear_cache
    return wrapper

使用示例:

python 复制代码
@average_time_decorator
def my_function():
    time.sleep(1)

# 调用函数
my_function()
my_function()

# 获取平均用时
print(f"平均用时: {my_function.get_avg_time():.6f} 秒")

# 清空缓存
my_function.clear_cache()

这样,装饰器就能正确记录函数的用时,并提供获取平均用时和清空缓存的功能。

nolocal 关键字

nonlocal 关键字在 Python 中用于声明一个变量不是局部变量,而是来自包含它的直接外部函数的作用域。它只会影响直接上层函数的变量,而不会跨越多个层次。

示例

考虑以下多层嵌套的函数:

python 复制代码
def outer_function():
    x = 10
    
    def middle_function():
        x = 20
        
        def inner_function():
            nonlocal x
            x = 30
            print("Inner function x:", x)
        
        inner_function()
        print("Middle function x:", x)
    
    middle_function()
    print("Outer function x:", x)

outer_function()

输出将是:

复制代码
Inner function x: 30
Middle function x: 30
Outer function x: 10

在这个例子中:

  1. inner_function 中的 nonlocal x 声明了 x 是来自 middle_function 的变量。
  2. inner_function 中的 x = 30 语句修改了 middle_function 中的 x,使其从 20 变为 30。
  3. outer_function 中的 x 保持不变,仍然是 10。

总结

nonlocal 关键字只会影响直接上层函数的变量,而不会跨越多个层次。如果你需要修改更外层函数的变量,你需要在每一层都使用 nonlocal 声明。

相关推荐
用户03321266636740 分钟前
使用 Python 在 Excel 中添加与删除筛选器
python·excel
1M5544 分钟前
AI应用后端工程(03):回答输出一半就断了:AI 流式接口如何定义成功与失败?
python·面试·职场和发展·计算机专业·agent开发
AI 编程助手GPT2 小时前
GPT 排的日志时间线差一小时?用 zoneinfo 复现夏令时回拨
人工智能·python·gpt
Thanks_ks2 小时前
【第 003 讲】全面认识 Python:语言起源与设计哲学 | 行业地位与流行趋势 | 技术优势与应用领域 | 技术边界与工程局限
人工智能·python·数据分析·编程语言·python 入门·web 开发·python 之禅
用户790860057262 小时前
给 AI 装上耳朵:离线语音识别与唤醒,国内环境踩坑实录
python
用户790860057262 小时前
我让 AI 自己上了趟网:browser-use 的三个致命坑和 CDP 混合方案
python
安枳杦2 小时前
把一个 FastAPI 网页塞进 macOS 的 Dock:Tauri 2 + PyInstaller 实战
python
像风一样自由20202 小时前
3.Dockerfile如何构建一个Python算法镜像
开发语言·人工智能·python·大模型
Dmz丶3 小时前
前端转 AI 100 天 Day 36:Prompt 工程入门——从“感觉对了就行”到方法论
python
日日大王学编程3 小时前
AI 时代后端方向新人的未来规划与看法
人工智能·后端·python·ai·golang