Skip to content

Instantly share code, notes, and snippets.

@loadx
Created May 2, 2018 15:38
Show Gist options
  • Save loadx/bc3643304238e44132f14a5b629f0173 to your computer and use it in GitHub Desktop.
Save loadx/bc3643304238e44132f14a5b629f0173 to your computer and use it in GitHub Desktop.
concurrency examples
import asyncio
import timeit
from functools import partial
from multiprocessing import Pool
from test_multi_sock import print_at_interval, print_at_async_interval
runs = 10
sample_vals = ["hello", "world", "done"]
loop = asyncio.get_event_loop()
def single_exec():
for i in sample_vals:
print_at_interval(i, 2)
def multi_process():
with Pool(3) as p:
p.map(partial(print_at_interval, interval=2), sample_vals)
async def a_exec():
for i in sample_vals:
res = await print_at_async_interval(i, 2)
def do_async_job():
loop.run_until_complete(a_exec())
res = timeit.timeit('single_exec()', globals=globals(), number=runs)
print("single:\n{}\n".format(res))
res = timeit.timeit('multi_process()', globals=globals(), number=runs)
print("multiproc:\n{}\n".format(res))
res = timeit.timeit('do_async_job()', globals=globals(), number=runs)
loop.close()
print("async:\n{}\n".format(res))
import asyncio
import time
def print_at_interval(message, interval=1):
time.sleep(interval)
print("Done for: {}".format(message))
async def print_at_async_interval(message, interval=1):
asyncio.sleep(interval)
print("Done for: {}".format(message))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment