Created
July 31, 2024 19:30
-
-
Save 0xquad/7932fb4794976cf2169dabcfdde99e12 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
# Small snippet of code to demonstrate fetching remote resources in parallel | |
import asyncio | |
import aiohttp | |
import random | |
import time | |
async def req(session, delay): | |
url = f'http://httpbin.org/delay/{delay}' | |
async with session.get(url) as resp: | |
result = (resp.status, await resp.text()) | |
return result | |
async def main(): | |
conn = aiohttp.TCPConnector(limit=20) | |
async with aiohttp.ClientSession(connector=conn) as sess: | |
tasks = [] | |
for i in range(40): | |
delay = random.uniform(.5, 5.5) | |
tasks.append(req(sess, delay)) | |
await asyncio.gather(*tasks) | |
start = time.time() | |
asyncio.run(main()) | |
print(f'duration: {time.time() - start}') | |
# Sample output: | |
# $ python parallel.py | |
# duration: 10.057737827301025 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment