experimental success

This commit is contained in:
Jörn-Michael Miehe 2023-09-08 16:08:10 +00:00
parent 5223efddb4
commit e894aad746

View file

@ -1,38 +1,32 @@
import asyncio import asyncio
import functools import functools
from contextlib import asynccontextmanager, contextmanager
from io import BytesIO from io import BytesIO
from typing import AsyncContextManager, AsyncIterator, ContextManager, Iterator
from cache import AsyncLRU from cache import AsyncLRU
FILES = __file__, "pyproject.toml"
REPS = 3
# #
# sync impl # sync impl
# #
def get_buf_sync() -> ContextManager[BytesIO]:
if getattr(get_buf_sync, "inner", None) is None:
@functools.lru_cache @functools.lru_cache
def inner() -> bytes: def get_bytes_sync(fn) -> bytes:
print("sync open") print("sync open")
with open(__file__, "rb") as file: with open(fn, "rb") as file:
return file.readline() return file.readline()
setattr(get_buf_sync, "inner", inner)
@contextmanager def get_buf_sync(fn) -> BytesIO:
def ctx() -> Iterator[BytesIO]: return BytesIO(get_bytes_sync(fn))
yield BytesIO(get_buf_sync.inner())
return ctx()
def main_sync() -> None: def main_sync() -> None:
for _ in range(2): for fn in FILES:
with get_buf_sync() as buffer: for _ in range(REPS):
print(buffer.read()) print(get_buf_sync(fn).read())
# #
@ -40,28 +34,21 @@ def main_sync() -> None:
# #
async def get_buf_async() -> AsyncContextManager[BytesIO]:
if getattr(get_buf_async, "inner", None) is None:
@AsyncLRU() @AsyncLRU()
async def inner() -> bytes: async def get_bytes_async(fn) -> bytes:
print("async open") print("async open")
with open(__file__, "rb") as file: with open(fn, "rb") as file:
return file.readline() return file.readline()
setattr(get_buf_async, "inner", inner)
@asynccontextmanager async def get_buf_async(fn) -> BytesIO:
async def ctx() -> AsyncIterator[BytesIO]: return BytesIO(await get_bytes_async(fn))
yield BytesIO(await get_buf_async.inner())
return ctx()
async def main_async() -> None: async def main_async() -> None:
for _ in range(2): for fn in FILES:
async with await get_buf_async() as buffer: for _ in range(REPS):
print(buffer.read()) print((await get_buf_async(fn)).read())
if __name__ == "__main__": if __name__ == "__main__":