Skip to content

Instantly share code, notes, and snippets.

@Zwork101
Created February 26, 2018 01:10
Show Gist options
  • Save Zwork101/5d9757995bd2d1868c2826b9bfd8c6b7 to your computer and use it in GitHub Desktop.
Save Zwork101/5d9757995bd2d1868c2826b9bfd8c6b7 to your computer and use it in GitHub Desktop.
Threading vs Asyncio, edited version of this artical: https://hackernoon.com/asyncio-for-the-working-python-developer-5c468e6e2e8e
import time
import threading
import requests
import asyncio
import aiohttp
URL = 'https://google.com'
MAX_CLIENTS = 500
def fetch_sync(pid):
print('Fetch thread process {} started'.format(pid))
start = time.time()
t = threading.Thread(target=requests.get, args=[URL])
t.start()
print('Process {}: took: {:.2f} seconds'.format(
pid, time.time() - start))
async def fetch_async(pid):
print('Fetch async process {} started'.format(pid))
start = time.time()
async with aiohttp.ClientSession() as sess:
response = await sess.get(URL)
print('Process {}: took: {:.2f} seconds'.format(
pid, time.time() - start))
response.close()
def synchronous():
start = time.time()
for i in range(1, MAX_CLIENTS + 1):
fetch_sync(i)
print("Process took: {:.2f} seconds".format(time.time() - start))
async def asynchronous():
start = time.time()
tasks = [asyncio.ensure_future(
fetch_async(i)) for i in range(1, MAX_CLIENTS + 1)]
await asyncio.wait(tasks)
print("Process took: {:.2f} seconds".format(time.time() - start))
print('Synchronous:')
synchronous()
print('Asynchronous:')
ioloop = asyncio.ProactorEventLoop()
ioloop.run_until_complete(asynchronous())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment