Created
August 9, 2024 14:21
-
-
Save olidroide/add47bf1134bb0a2112b11aa8292edc9 to your computer and use it in GitHub Desktop.
Ejemplo lru_cache Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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