forked from ls1248659692/python_guide
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasyncio_run.py
More file actions
81 lines (56 loc) · 1.57 KB
/
asyncio_run.py
File metadata and controls
81 lines (56 loc) · 1.57 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
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/python
# coding=utf8
import asyncio
import time
import aiohttp
import requests
__author__ = 'Jam'
__date__ = '2019/7/5 17:33'
def job(t):
print('Start job ', t)
time.sleep(t)
print('Job ', t, ' takes ', t, ' s')
def main():
[job(t) for t in range(1, 10)]
t1 = time.time()
main()
print("NO async total time : ", time.time() - t1)
print('*1*'.center(50, '-'))
async def job(t):
print('Start job ', t)
await asyncio.sleep(t)
print('Job ', t, ' takes ', t, ' s')
async def main(loop):
tasks = [loop.create_task(job(t)) for t in range(1, 10)]
await asyncio.wait(tasks)
t1 = time.time()
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
loop.close()
print("Async total time : ", time.time() - t1)
print('*2*'.center(50, '-'))
URL = 'https://morvanzhou.github.io/'
def normal():
for i in range(2):
r = requests.get(URL)
url = r.url
print(url)
t1 = time.time()
normal()
print("Normal total time:", time.time() - t1)
print('*3*'.center(50, '-'))
async def job(session):
response = await session.get(URL)
return str(response.url)
async def normal_main(loop):
async with aiohttp.ClientSession() as session:
tasks = [loop.create_task(job(session)) for _ in range(2)]
finished, unfinished = await asyncio.wait(tasks)
all_results = [r.result() for r in finished]
print(all_results)
t1 = time.time()
loop = asyncio.get_event_loop()
loop.run_until_complete(normal_main(loop))
loop.close()
print("Async total time:", time.time() - t1)
print('*4*'.center(50, '-'))