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

相关推荐
猿界零零七7 小时前
pip install mxnet 报错解决方案
python·pip·mxnet
不只会拍照的程序猿8 小时前
《嵌入式AI筑基笔记02:Python数据类型01,从C的“硬核”到Python的“包容”》
人工智能·笔记·python
Jay_Franklin9 小时前
Quarto与Python集成使用
开发语言·python·markdown
Oueii9 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
2401_8318249610 小时前
使用Fabric自动化你的部署流程
jvm·数据库·python
njidf10 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python
@我漫长的孤独流浪10 小时前
Python编程核心知识点速览
开发语言·数据库·python
宇擎智脑科技10 小时前
A2A Python SDK 源码架构解读:一个请求是如何被处理的
人工智能·python·架构·a2a
2401_8512729910 小时前
实战:用Python分析某电商销售数据
jvm·数据库·python
vx_biyesheji000110 小时前
Python 全国城市租房洞察系统 Django框架 Requests爬虫 可视化 房子 房源 大数据 大模型 计算机毕业设计源码(建议收藏)✅
爬虫·python·机器学习·django·flask·课程设计·旅游