请设计一个自定义的缓存机制,用于优化循环中的重复计算,并比较其与内置缓存工具的性能差异。

# 自定义缓存机制的实现

class CustomCache:
    def __init__(self):
        self._cache = {}

    def get(self, key):
        return self._cache.get(key, None)

    def set(self, key, value):
        self._cache[key] = value

    def clear(self):
        self._cache.clear()

# 使用自定义缓存优化重复计算

def fibonacci(n, cache=None):
    if cache is None:
        cache = CustomCache()
    
    if n <= 1:
        return n
    
    cached_result = cache.get(n)
    if cached_result is not None:
        return cached_result
    
    result = fibonacci(n - 1, cache) + fibonacci(n - 2, cache)
    cache.set(n, result)
    return result

# 示例:计算斐波那契数列
print(fibonacci(10))  # 输出:55


# 内置缓存工具(如 functools.lru_cache)的对比
from functools import lru_cache

@lru_cache(maxsize=None)
def fib_lru(n):
    if n <= 1:
        return n
    return fib_lru(n - 1) + fib_lru(n - 2)

# 示例:计算斐波那契数列
print(fib_lru(10))  # 输出:55


# 性能比较
import time

# 测试自定义缓存
def test_custom_cache():
    start_time = time.time()
    for i in range(30):
        fibonacci(i)
    end_time = time.time()
    return end_time - start_time

# 测试内置缓存
def test_lru_cache():
    start_time = time.time()
    fib_lru.cache_clear()  # 清空缓存以公平比较
    for i in range(30):
        fib_lru(i)
    end_time = time.time()
    return end_time - start_time

custom_time = test_custom_cache()
lru_time = test_lru_cache()

print(f"自定义缓存时间: {custom_time} 秒")
print(f"内置缓存时间: {lru_time} 秒")

# 结果分析
# 通常情况下,内置的 lru_cache 会比自定义缓存更快,因为它是用 C 语言实现的,且经过了高度优化。
# 自定义缓存更适合需要特殊逻辑的场景,例如缓存部分结果或动态调整缓存策略。

# 扩展:自定义缓存的优化方向
# 1. 增加缓存过期时间
# 2. 动态调整缓存大小
# 3. 支持多线程安全

# 示例:带过期时间的自定义缓存
class TimedCache:
    def __init__(self, ttl=60):
        self._cache = {}
        self._ttl = ttl

    def get(self, key):
        entry = self._cache.get(key)
        if entry and (time.time() - entry['timestamp']) < self._ttl:
            return entry['value']
        return None

    def set(self, key, value):
        self._cache[key] = {'value': value, 'timestamp': time.time()}

# 使用带过期时间的缓存
cache = TimedCache(ttl=10)
cache.set('key', 'value')
print(cache.get('key'))  # 10 秒内会返回 'value'

总结

  1. 自定义缓存的优势在于灵活性,可以根据需求实现特定功能,但性能通常不如内置缓存工具。
  2. **内置缓存(如 lru_cache)**的优势在于性能优化和易用性,适合大多数通用场景。
  3. 选择建议:如果需求简单,优先使用内置缓存;如果需要定制化功能,则考虑自定义缓存。