Python中利用装饰器优化函数性能的实用技巧

```python

import time

import functools

from typing import Callable, Any

# 1. 缓存装饰器 - 避免重复计算

def cache_decorator(func: Callable) -> Callable:

缓存装饰器,存储函数计算结果

cache = {}

@functools.wraps(func)

def wrapper(args, kwargs):

# 创建缓存键

key = str(args) + str(sorted(kwargs.items()))

if key not in cache:

cache[key] = func(args, kwargs)

return cache[key]

return wrapper

# 2. 超时装饰器 - 防止函数执行时间过长

def timeout_decorator(timeout_seconds: float):

设置函数执行超时时间

def decorator(func: Callable) -> Callable:

@functools.wraps(func)

def wrapper(args, kwargs):

start_time = time.time()

result = func(args, kwargs)

end_time = time.time()

execution_time = end_time - start_time

if execution_time > timeout_seconds:

print(f警告: 函数 {func.__name__} 执行时间过长: {execution_time:.2f}秒)

return result

return wrapper

return decorator

# 3. 重试装饰器 - 自动重试失败的操作

def retry_decorator(max_retries: int = 3, delay: float = 1.0):

自动重试装饰器

def decorator(func: Callable) -> Callable:

@functools.wraps(func)

def wrapper(args, kwargs):

for attempt in range(max_retries):

try:

return func(args, kwargs)

except Exception as e:

if attempt == max_retries - 1:

raise e

print(f尝试 {attempt + 1} 失败: {e}, {delay}秒后重试...)

time.sleep(delay)

return None

return wrapper

return decorator

# 4. 性能监控装饰器

def performance_monitor(func: Callable) -> Callable:

监控函数执行性能

@functools.wraps(func)

def wrapper(args, kwargs):

start_time = time.perf_counter()

start_memory = ... # 这里可以添加内存监控

result = func(args, kwargs)

end_time = time.perf_counter()

execution_time = end_time - start_time

print(f函数 {func.__name__} 执行时间: {execution_time:.6f}秒)

return result

return wrapper

# 5. 参数验证装饰器

def validate_arguments(func: Callable) -> Callable:

验证函数参数类型和范围

@functools.wraps(func)

def wrapper(args, kwargs):

# 这里可以添加具体的参数验证逻辑

# 例如检查参数类型、范围等

# 简单的示例:检查参数是否为空

for i, arg in enumerate(args):

if arg is None:

raise ValueError(f第 {i+1} 个参数不能为 None)

for key, value in kwargs.items():

if value is None:

raise ValueError(f参数 {key} 不能为 None)

return func(args, kwargs)

return wrapper

# 6. 组合装饰器 - 批量应用多个装饰器

def compose_decorators(decorators):

组合多个装饰器

def decorator(func):

for dec in reversed(decorators):

func = dec(func)

return func

return decorator

# 使用示例

@compose_decorators(

cache_decorator,

timeout_decorator(5.0),

performance_monitor,

validate_arguments

)

def fibonacci(n: int) -> int:

计算斐波那契数列

if n <= 1:

return n

return fibonacci(n-1) + fibonacci(n-2)

@retry_decorator(max_retries=3, delay=0.5)

def api_call_simulation():

模拟API调用,可能失败

import random

if random.random() < 0.7:

raise ConnectionError(API调用失败)

return 成功

# 测试代码

if __name__ == __main__:

# 测试缓存装饰器

print(斐波那契数列测试:)

print(ffibonacci(10) = {fibonacci(10)})

print(ffibonacci(10) = {fibonacci(10)}) # 第二次调用应该从缓存中读取

print( 重试装饰器测试:)

try:

result = api_call_simulation()

print(fAPI调用结果: {result})

except Exception as e:

print(f最终失败: {e})

# 7. 内存缓存装饰器(使用LRU缓存)

@functools.lru_cache(maxsize=128)

def expensive_computation(x: int, y: int) -> int:

昂贵的计算函数

time.sleep(0.1) # 模拟耗时操作

return x y + x 2

# 8. 条件缓存装饰器

def conditional_cache(condition_func: Callable):

根据条件决定是否缓存

def decorator(func: Callable) -> Callable:

cache = {}

@functools.wraps(func)

def wrapper(args, kwargs):

if condition_func(args, kwargs):

key = str(args) + str(sorted(kwargs.items()))

if key not in cache:

cache[key] = func(args, kwargs)

return cache[key]

else:

return func(args, kwargs)

return wrapper

return decorator

# 9. 异步函数性能监控

def async_performance_monitor(func: Callable) -> Callable:

异步函数性能监控装饰器

@functools.wraps(func)

async def wrapper(args, kwargs):

start_time = time.perf_counter()

result = await func(args, kwargs)

end_time = time.perf_counter()

execution_time = end_time - start_time

print(f异步函数 {func.__name__} 执行时间: {execution_time:.6f}秒)

return result

return wrapper

# 实用技巧总结:

1. 使用 @functools.wraps 保持函数元信息

2. 合理使用缓存避免重复计算

3. 设置超时防止函数阻塞

4. 实现自动重试提高稳定性

5. 监控性能识别瓶颈

6. 验证参数提高代码健壮性

7. 组合装饰器保持代码整洁

8. 针对不同场景选择合适的缓存策略

9. 支持同步和异步函数

# 性能优化建议:

- 对于计算密集型函数,使用缓存可以显著提升性能

- 对于I/O密集型函数,考虑使用异步装饰器

- 合理设置缓存大小,避免内存泄漏

- 在生产环境中,可以添加日志记录而不是直接打印

- 根据具体业务需求定制装饰器逻辑

print( 性能优化装饰器使用完成!)

```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值