Created
May 2, 2018 15:38
-
-
Save loadx/bc3643304238e44132f14a5b629f0173 to your computer and use it in GitHub Desktop.
concurrency examples
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
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)) |
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
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