Skip to content

Instantly share code, notes, and snippets.

@jdevera
Created October 25, 2018 10:00
Show Gist options
  • Save jdevera/5e98110c0818e71cfe2f57c4bff25d4b to your computer and use it in GitHub Desktop.
Save jdevera/5e98110c0818e71cfe2f57c4bff25d4b to your computer and use it in GitHub Desktop.
Sync vs Async comparison in Python
import asyncio
import argparse
counter = 0
def next():
global counter
counter += 1
return counter
async def get(url):
id = next()
delay = 2 if 'job' in url else 4
print(f'{id}: Getting url and taking a sweeeet time ({delay} s): ', url)
await asyncio.sleep(delay)
print(f'{id}: Got the URL {url}')
return (id, '{OK}')
async def get_job(args, job):
id = next()
print(f'{id}: get_job({job}) -> gonna wait')
resp = await get(f'http://job/{job}.com')
print(f'{id}: get_job({job}) -> returned {resp}')
builds_nums = list(range(args.builds))
results = await asyncio.gather(*[get_build(job, build) for build in builds_nums])
builds = dict(zip(builds_nums, results))
return resp, builds
async def get_build(job, build):
id = next()
print(f'{id}: get_build({job}, {build}) -> gonna wait')
resp = await get(f'http://build/{job}-{build}.com')
print(f'{id}: get_build({job}, {build}) -> returned {resp}')
return resp
async def runall(args):
tasks = []
for job in range(args.jobs):
tasks.append(get_job(args, job))
result = await asyncio.gather(*tasks)
print(result)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('jobs', type=int)
parser.add_argument('builds', type=int)
return parser.parse_args()
args = parse_args()
loop = asyncio.get_event_loop()
loop.run_until_complete(runall(args))
loop.close()
import time
import argparse
counter = 0
def next():
global counter
counter += 1
return counter
def get(url):
id = next()
delay = 2 if 'job' in url else 4
print(f'{id}: Getting url and taking a sweeeet time ({delay} s): ', url)
time.sleep(delay)
print(f'{id}: Got the URL {url}')
return (id, '{OK}')
def get_job(args, job):
id = next()
print(f'{id}: get_job({job}) -> gonna wait')
resp = get(f'http://job/{job}.com')
print(f'{id}: get_job({job}) -> returned {resp}')
builds_nums = list(range(args.builds))
results = [get_build(job, build) for build in builds_nums]
builds = dict(zip(builds_nums, results))
return resp, builds
def get_build(job, build):
id = next()
print(f'{id}: get_build({job}, {build}) -> gonna wait')
resp = get(f'http://build/{job}-{build}.com')
print(f'{id}: get_build({job}, {build}) -> returned {resp}')
return resp
def runall(args):
result = []
for job in range(args.jobs):
result.append(get_job(args, job))
print(result)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('jobs', type=int)
parser.add_argument('builds', type=int)
return parser.parse_args()
args = parse_args()
runall(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment