Last active
April 18, 2019 22:52
-
-
Save okiwan/2209c1aeeedf70679ff3df6bec2fa4a2 to your computer and use it in GitHub Desktop.
Asyncio simple demonstration
This file contains 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
""" | |
The idea of this piece of code is to demonstrate how asyncio | |
works so you can understand the benefits of using it in your | |
IO-demansind apps. | |
The application creates a defined number of workers that will | |
generate a request to a website for a randomly-generated numbers | |
and will return the sum. | |
Note that when running the code workers will be created immediately, | |
then the application will wait until all results are available and | |
finally returning the list of sums. | |
You may vary the number of workers and see the impact in time. | |
You should see that a higher number of workers do not impact that | |
much in the amount of time your application takes to run. Of course | |
the result may be altered by the way the accessed server operates. | |
""" | |
import asyncio | |
import json | |
import time | |
import aiohttp | |
async def worker(name, n, session): | |
print(f'worker-{name}') | |
url = f'https://qrng.anu.edu.au/API/jsonI.php?length={n}&type=uint16' | |
response = await session.request(method='GET', url=url) | |
value = json.loads(await response.text()) | |
return sum(value['data']) | |
async def main(): | |
async with aiohttp.ClientSession() as session: | |
sums = await asyncio.gather(*(worker(i, n, session) for i, n in enumerate(range(2, 20)))) | |
print(f'sums: {sums}') | |
if __name__ == '__main__': | |
start = time.perf_counter() | |
asyncio.run(main()) | |
elapsed = time.perf_counter() - start | |
print(f'executed in {elapsed:0.2f} seconds.') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment