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 声明。

相关推荐
love530love1 小时前
Windows 下 Z-Image-Turbo 专业版 Gradio 生成器实战:功能增强全记录
人工智能·windows·python·大模型·gradio·博客之星·z-image
人工干智能2 小时前
Chat Completions API中的三种role:“system“,“user“,“assistant“
python·llm
Darenm1112 小时前
JWT鉴权的实现:从原理到 Django + Vue3
后端·python·django
Funny_AI_LAB2 小时前
Zcode:智谱AI推出的轻量级 AI IDE 编程利器
人工智能·python·算法·编辑器
2501_944452232 小时前
活动记录 Cordova 与 OpenHarmony 混合开发实战
python
子夜江寒2 小时前
基于 Python 使用 SVM、K-means与DBSCAN
python·支持向量机·kmeans
Blossom.1182 小时前
GPTQ量化实战:从零手写大模型权重量化与反量化引擎
人工智能·python·算法·chatgpt·ai作画·自动化·transformer
Elaine3362 小时前
实战教学:使用 Scrapy 爬取 CSDN 文章与用户头像
python·scrapy·网络爬虫
程序员佳佳3 小时前
文章标题:彻底抛弃OpenAI官方Key?实测GPT-5.2与Banana Pro(Gemini 3):这才是开发者的终极红利!
开发语言·人工智能·python·gpt·ai作画·api·midjourney
qq_356196953 小时前
day49_通道注意力机制 @浙大疏锦行
python