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

相关推荐
monster000w7 分钟前
容器云2.7pytorch版本安装问题
人工智能·pytorch·python
Cherry的跨界思维8 分钟前
19、自动化处理双核心:Java规则引擎与Python Selenium实战全解析
java·开发语言·python·自动化·办公自动化·python办公自动化·python办公
互亿无线明明1 小时前
国际短信通知服务:如何为全球业务构建稳定的跨国消息触达体系?
java·c语言·python·php·objective-c·ruby·composer
相思半1 小时前
数据偏见去偏方法系统方法论学习(基础知识+实践运用)-新手友好版
大数据·人工智能·python·深度学习·机器学习·数据分析
黑客思维者1 小时前
Python自动化测试Pytest/Unittest深度解析与接口测试落地实践
开发语言·python·pytest·unittest
鲁邦通物联网1 小时前
工业边缘网关+Python:实现PLC数据采集的微服务化
python·数据采集·工业数据采集·边缘网关·边缘计算网关·5g数采
中等生1 小时前
深入理解 Gunicorn
python·uwsgi
IT运维爱好者1 小时前
【Linux】Python3 环境的下载与安装
linux·python·centos7
码界奇点2 小时前
基于Django REST framework与Vue的前后端分离后台管理系统设计与实现
vue.js·后端·python·django·毕业设计·源代码管理
倔强的小石头_2 小时前
Python 从入门到实战(六):字典(关联数据的 “高效管家”)
java·服务器·python