Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. import asyncio
  2. import time
  3. import typing
  4.  
  5.  
  6. async def say(t: int, word):
  7. await asyncio.sleep(t)
  8. print(word)
  9. return word
  10.  
  11.  
  12. async def non_parallel():
  13. await say(1, 1)
  14. await say(2, 2)
  15.  
  16.  
  17. async def parallel():
  18. task1 = asyncio.create_task(say(1, 1))
  19. task2 = asyncio.create_task(say(2, 2))
  20.  
  21. result1 = await task1
  22. result2 = await task2
  23. print(result1, result2)
  24.  
  25.  
  26. def run(func: typing.Callable):
  27. s = time.time()
  28. asyncio.run(func())
  29. print(f'{func.__name__}: {(time.time() - s):.2f} sec')
  30.  
  31.  
  32. def event_loop():
  33. s = time.time()
  34. loop = asyncio.get_event_loop()
  35. t1, t2 = loop.run_until_complete(asyncio.gather(say(1, 'task1'),
  36. say(2, 'task2')))
  37. print(t1, t2)
  38. print(f'event_loop: {(time.time() - s):.2f} sec')
  39.  
  40.  
  41. if __name__ == '__main__':
  42. # Don't run asyncio.get_event_loop() after asyncio.run()
  43. event_loop()
  44.  
  45. run(parallel)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement