Skip to content

Instantly share code, notes, and snippets.

@olidroide
Created August 9, 2024 14:21
Show Gist options
  • Select an option

  • Save olidroide/add47bf1134bb0a2112b11aa8292edc9 to your computer and use it in GitHub Desktop.

Select an option

Save olidroide/add47bf1134bb0a2112b11aa8292edc9 to your computer and use it in GitHub Desktop.
Ejemplo lru_cache Python
import time
import timeit
from functools import lru_cache
@lru_cache(maxsize=32)
def long_process(user_id: int) -> int:
time.sleep(0.01)
return 1
def test_cached() -> None:
user_id = 1
iterations = 50
for _ in range(iterations):
long_process(user_id)
cache_info = long_process.cache_info()
print(f"cache hits: {cache_info.hits}")
print(f"cache size: {cache_info.currsize} must be 1")
def test_without_cached() -> None:
user_id = 1
iterations = 50
for _ in range(iterations):
long_process.cache_clear() # clear cache every iteration
long_process(user_id)
time_with_cache = timeit.timeit("test_cached()", globals=globals(), number=1)
time_without_cache = timeit.timeit("test_without_cached()", globals=globals(), number=1)
print(f"Without cache: {time_without_cache:.2f} sec")
print(f"With cache: {time_with_cache:.2f} sec")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment