-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWS12-asyncio.py
More file actions
69 lines (53 loc) · 1.27 KB
/
WS12-asyncio.py
File metadata and controls
69 lines (53 loc) · 1.27 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import random
from time import sleep
import asyncio
import time
import warnings
warnings.filterwarnings("ignore")
n = 50000000
constn = n
def countdown(k):
global n
for _ in range(k):
n -= 1
sleep(0.1)
print('Subtracted %s' % k)
async def asyncountdown(k):
global n
async with sem:
for _ in range(k):
n -= 1
await asyncio.sleep(random.randint(0, 2) * 0.2)
# await asyncio.sleep(0.1)
print('Subtracted %s' % k)
def task(pid):
"""Synchronous non-deterministic task.
"""
sleep(0.2) # random.randint(0, 2) *
print('Task %s done' % pid)
async def task_coro(pid):
"""Coroutine non-deterministic task
"""
await asyncio.sleep(0.2)
print('Task %s done' % pid)
def synchronous():
for i in range(10):
countdown(constn // 10 - i)
async def asynchronous():
tasks = [asyncio.ensure_future(asyncountdown(constn // 10 - i)) for i in range(10)]
await asyncio.wait(tasks)
print(n)
print('Synchronous:')
start = time.time()
synchronous()
print(time.time() - start)
print(n)
n = 50000000
ioloop = asyncio.get_event_loop()
sem = asyncio.Semaphore(constn)
print('Asynchronous:')
start = time.time()
ioloop.run_until_complete(asynchronous())
ioloop.close()
print(time.time() - start)
print(n)