-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWS11-asyncio.py
More file actions
41 lines (30 loc) · 803 Bytes
/
WS11-asyncio.py
File metadata and controls
41 lines (30 loc) · 803 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import random
from time import sleep
import asyncio
import time
def task(pid):
"""Synchronous non-deterministic task.
"""
sleep(random.randint(0, 2) * 0.2)
print('Task %s done' % pid)
async def task_coro(pid):
"""Coroutine non-deterministic task
"""
await asyncio.sleep(random.randint(0, 2) * 0.2)
print('Task %s done' % pid)
def synchronous():
for i in range(1, 10):
task(i)
async def asynchronous():
tasks = [asyncio.ensure_future(task_coro(i)) for i in range(1, 10)]
await asyncio.wait(tasks)
print('Synchronous:')
start = time.time()
synchronous()
print(time.time() - start)
ioloop = asyncio.get_event_loop()
print('Asynchronous:')
start = time.time()
ioloop.run_until_complete(asynchronous())
ioloop.close()
print(time.time() - start)