Created
July 31, 2024 05:15
-
-
Save WomB0ComB0/5c4b23d20787315e1c5ded47d3207d9b to your computer and use it in GitHub Desktop.
Meoize class 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
class Memoize: | |
def __init__(self, func: Callable) -> None: | |
self.func = func | |
self.cache = {} | |
def __call__(self, *args, **kwargs) -> Any: | |
if args not in self.cache: | |
self.cache[args] = self.func(*args, **kwargs) | |
return self.cache[args] | |
def memory_allocated(self) -> int: | |
return sys.getsizeof(self.cache) | |
def memory_allocated_in_mb(self) -> int: | |
return int(self.memory_allocated() / 1024 / 1024) | |
def memory_allocated_for_args(self, args: Tuple[Any, ...]) -> int: | |
return sys.getsizeof(args) | |
def memory_allocated_for_args_in_mb(self, args: Tuple[Any, ...]) -> int: | |
return int(self.memory_allocated_for_args(args) / 1024 / 1024) | |
def memory_allocated_loop( | |
self, func: Callable, args: Tuple[Any, ...], iterations: int | |
) -> int: | |
return sys.getsizeof(func(*args) for _ in range(iterations)) | |
def memory_allocated_loop_in_mb( | |
self, func: Callable, args: Tuple[Any, ...], iterations: int | |
) -> int: | |
return int(self.memory_allocated_loop(func, args, iterations) / 1024 / 1024) | |
def clear_cache(self) -> str: | |
cache_size = self.memory_allocated() | |
self.cache = {} | |
return f"Cleared cache. Memory allocated: {cache_size} bytes" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment