advent22/api/asynccontextmanager.py

57 lines
944 B
Python
Raw Normal View History

import asyncio
import functools
from io import BytesIO
2023-09-08 15:54:11 +00:00
from cache import AsyncLRU
2023-09-08 16:08:10 +00:00
FILES = __file__, "pyproject.toml"
REPS = 3
2023-09-08 15:54:11 +00:00
#
# sync impl
#
2023-09-08 16:08:10 +00:00
@functools.lru_cache
def get_bytes_sync(fn) -> bytes:
print("sync open")
with open(fn, "rb") as file:
return file.readline()
2023-09-08 16:08:10 +00:00
def get_buf_sync(fn) -> BytesIO:
return BytesIO(get_bytes_sync(fn))
def main_sync() -> None:
2023-09-08 16:08:10 +00:00
for fn in FILES:
for _ in range(REPS):
print(get_buf_sync(fn).read())
2023-09-08 15:54:11 +00:00
#
# async impl
#
2023-09-08 16:08:10 +00:00
@AsyncLRU()
async def get_bytes_async(fn) -> bytes:
print("async open")
with open(fn, "rb") as file:
return file.readline()
2023-09-08 16:08:10 +00:00
async def get_buf_async(fn) -> BytesIO:
return BytesIO(await get_bytes_async(fn))
async def main_async() -> None:
2023-09-08 16:08:10 +00:00
for fn in FILES:
for _ in range(REPS):
print((await get_buf_async(fn)).read())
if __name__ == "__main__":
main_sync()
asyncio.run(main_async())