PHpullh

PYTHON · 성능

캐싱 전략

다양한 캐싱 전략으로 반복 계산을 제거하고 응답 속도를 향상시킵니다.

성능중급cache캐싱LRUTTL

핵심 설명

다양한 캐싱 전략으로 반복 계산을 제거하고 응답 속도를 향상시킵니다.

Python code

from functools import lru_cache
from collections import OrderedDict
import time

# 1. lru_cache (가장 간단)
@lru_cache(maxsize=256)
def expensive_calc(n: int) -> int:
    time.sleep(0.001)  # 비용이 큰 계산 시뮬레이션
    return n ** 2 + n

# 2. TTL 캐시 (시간 제한)
class TTLCache:
    def __init__(self, ttl_seconds: float = 60.0):
        self._cache: dict = {}
        self._ttl = ttl_seconds

    def get(self, key, default=None):
        if key in self._cache:
            value, timestamp = self._cache[key]
            if time.time() - timestamp < self._ttl:
                return value
            del self._cache[key]
        return default

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

# 3. LRU 캐시 (수동 구현)
class LRUCache:
    def __init__(self, capacity: int):
        self._cache = OrderedDict()
        self._capacity = capacity

    def get(self, key):
        if key in self._cache:
            self._cache.move_to_end(key)
            return self._cache[key]
        return None

    def put(self, key, value):
        if key in self._cache:
            self._cache.move_to_end(key)
        self._cache[key] = value
        if len(self._cache) > self._capacity:
            self._cache.popitem(last=False)

# 사용
cache = LRUCache(3)
cache.put("a", 1)
cache.put("b", 2)
cache.put("c", 3)
cache.get("a")      # a를 최근으로
cache.put("d", 4)   # b가 제거됨 (가장 오래됨)
print(f"a: {cache.get('a')}")  # 1
print(f"b: {cache.get('b')}")  # None (제거됨)

학습 팁

캐시 적중률이 낮으면 오히려 오버헤드가 됩니다. cache_info()로 적중률을 모니터링하세요.

주의할 점

캐시를 무효화하지 않으면 오래된 데이터를 반환합니다. TTL 또는 이벤트 기반 무효화를 구현하세요.

자주 묻는 질문

캐싱 전략란 무엇인가요?

다양한 캐싱 전략으로 반복 계산을 제거하고 응답 속도를 향상시킵니다.

캐싱 전략 학습 시 주의할 점은 무엇인가요?

캐시를 무효화하지 않으면 오래된 데이터를 반환합니다. TTL 또는 이벤트 기반 무효화를 구현하세요.