Skip to content

Instantly share code, notes, and snippets.

@Mastermind-U
Last active November 12, 2023 16:29
Show Gist options
  • Save Mastermind-U/2c790f356379e370f1cd8e52d642e82d to your computer and use it in GitHub Desktop.
Save Mastermind-U/2c790f356379e370f1cd8e52d642e82d to your computer and use it in GitHub Desktop.
Aysyncio memory benchmark for ensure_future vs create_task background coroutines
import asyncio
from memory_profiler import profile
SIZE = 100000
@profile
async def ensure_test():
loop = asyncio.get_running_loop()
tasks = [asyncio.ensure_future(asyncio.sleep(.1), loop=loop) for i in range(SIZE)]
await asyncio.sleep(0.1)
await asyncio.gather(*tasks)
@profile
async def task_test():
tasks = [asyncio.create_task(asyncio.sleep(.1)) for i in range(SIZE)]
await asyncio.sleep(0.1)
await asyncio.gather(*tasks)
if __name__ == '__main__':
asyncio.run(ensure_test())
asyncio.run(task_test())
pip install memory-profiler
python -m memory_profiler asyncio_background_benchmark.py
@Mastermind-U
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment