Skip to content

Instantly share code, notes, and snippets.

@Foxonn
Last active June 28, 2023 12:06
Show Gist options
  • Save Foxonn/e9ab8cbb8bbf6c4d72ae533cc935648d to your computer and use it in GitHub Desktop.
Save Foxonn/e9ab8cbb8bbf6c4d72ae533cc935648d to your computer and use it in GitHub Desktop.
Кэш управляемый единым классом
import time
import typing as t
from _functools import _lru_cache_wrapper
from functools import lru_cache
class LruCacheStorage(t.Dict[str, _lru_cache_wrapper]):
pass
class LruCacheManager:
__slots__ = (
'__storage',
)
def __init__(self):
self.__storage: LruCacheStorage = LruCacheStorage()
@property
def storage(self) -> LruCacheStorage:
return self.__storage
def get(self, key_cmd: str) -> _lru_cache_wrapper:
return self.__storage[key_cmd]
def register(self, key_cmd: str, cmd: t.Callable, maxsize: int = 256, typed: bool = False) -> _lru_cache_wrapper:
_ = lru_cache(maxsize=maxsize, typed=typed)(cmd)
self.__storage[key_cmd] = _
return _
class ITestCmd:
__slots__ = ()
def __call__(self, count: int) -> int:
raise NotImplementedError()
class TestCmd(ITestCmd):
__slots__ = ()
def __call__(self, count: int) -> int:
return sum([i for i in range(count)])
class TestCachedCmd(ITestCmd):
__slots__ = (
'__cached_cmd',
)
def __init__(self, cmd: TestCmd, lru_cache_manager: LruCacheManager):
self.__cached_cmd = lru_cache_manager.register(key_cmd='123', cmd=cmd)
def __call__(self, count: int) -> int:
return self.__cached_cmd(count)
lru_cache_manager = LruCacheManager()
cmd = TestCmd()
cached_cmd = TestCachedCmd(
cmd=cmd,
lru_cache_manager=lru_cache_manager
)
for i in range(5):
start = time.monotonic_ns()
cached_cmd(count=10000000)
print(f'Expiration time, find_match: {round((time.monotonic_ns() - start) / 1E7, 5)} ms.')
print('\n' + '*' * 30)
print(*[lru_cache_manager.get(key_cmd='123').cache_clear()], sep='\n\r')
print('*' * 30 + '\n')
for i in range(5):
start = time.monotonic_ns()
cached_cmd(count=10000000)
print(f'Expiration time, find_match: {round((time.monotonic_ns() - start) / 1E7, 5)} ms.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment