Skip to content

⚡️ Speed up function time_based_cache by 23% #74

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions src/dsa/caching_memoization.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,25 @@ def time_based_cache(expiry_seconds: int) -> Callable:
"""Manual implementation of a time-based cache decorator."""

def decorator(func: Callable) -> Callable:
cache: dict[str, tuple[Any, float]] = {}
cache: dict[tuple, tuple[Any, float]] = {}

def wrapper(*args, **kwargs) -> Any:
key_parts = [repr(arg) for arg in args]
key_parts.extend(f"{k}:{repr(v)}" for k, v in sorted(kwargs.items()))
key = ":".join(key_parts)
# Use hashable tuples for the cache key for speed
if kwargs:
key = (args, frozenset(kwargs.items()))
else:
key = (args, None)

current_time = time.time()

if key in cache:
result, timestamp = cache[key]
cached = cache.get(key)
if cached is not None:
result, timestamp = cached
if current_time - timestamp < expiry_seconds:
return result

result = func(*args, **kwargs)

cache[key] = (result, current_time)

return result

return wrapper
Expand Down Expand Up @@ -89,4 +90,4 @@ def knapsack(weights: list[int], values: list[int], capacity: int, n: int) -> in
return max(
values[n - 1] + knapsack(weights, values, capacity - weights[n - 1], n - 1),
knapsack(weights, values, capacity, n - 1),
)
)