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

相关推荐
XLYcmy8 小时前
京东 算法实习一面 下+手撕
c++·python·llm·概率论·数据处理·训练·codebert
虎头金猫8 小时前
如何在群晖NAS上通过Docker部署CloudSaver?群晖部署CloudSaver教程|聚合资源搜索并实现远程访问
运维·服务器·网络·python·docker·容器·pandas
从零开始学习人工智能8 小时前
WSL2部署CUDA12+cuDNN9踩坑实录:ONNX Runtime GPU推理环境搭建全流程
python
m0_380743878 小时前
从零调用 Claude 教程
开发语言·python·node.js
min(a,b)10 小时前
学习第17天:Agent Memory 与 MCP 协议
python·学习
CodeBlog-star10 小时前
LLM安全实战:提示词注入与越狱攻击防御指南
python·agent·提示词攻击·越狱攻击
小柯南敲键盘10 小时前
电商图片翻译工具推荐,批量处理主图视频字幕,免费试用
大数据·人工智能·python·音视频
比高创意品牌策划设计11 小时前
零售卖场设计软件用CAD还是SketchUp还是酷家乐
python
迷迭香yy13 小时前
行业板块轮动因子实战从板块资金到因子建模的本地化Python全流程
数据库·人工智能·python
W_3260013 小时前
Python文件进阶:一维数据与 CSV 文件读写
开发语言·python