Skip to content

Instantly share code, notes, and snippets.

@cocodrips
Created September 27, 2019 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cocodrips/7bb84962eb778009dd4f9444edada0fc to your computer and use it in GitHub Desktop.
Save cocodrips/7bb84962eb778009dd4f9444edada0fc to your computer and use it in GitHub Desktop.
Async練習
import asyncio
import time
import typing
async def say(t: int, word):
await asyncio.sleep(t)
print(word)
return word
async def non_parallel():
await say(1, 1)
await say(2, 2)
async def parallel():
task1 = asyncio.create_task(say(1, 1))
task2 = asyncio.create_task(say(2, 2))
result1 = await task1
result2 = await task2
print(result1, result2)
def run(func: typing.Callable):
s = time.time()
asyncio.run(func())
print(f'{func.__name__}: {(time.time() - s):.2f} sec')
def event_loop():
s = time.time()
loop = asyncio.get_event_loop()
t1, t2 = loop.run_until_complete(asyncio.gather(say(1, 'task1'),
say(2, 'task2')))
print(t1, t2)
print(f'event_loop: {(time.time() - s):.2f} sec')
if __name__ == '__main__':
# Don't run asyncio.get_event_loop() after asyncio.run()
event_loop()
run(parallel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment