-
Notifications
You must be signed in to change notification settings - Fork 4
/
async_demo.py
61 lines (49 loc) · 1.32 KB
/
async_demo.py
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
import asyncio
import time
import aiohttp
import requests
def fetch(session):
resp = session.get("https://github.com/fwkoch")
print(resp.status_code)
return resp.status_code
def fetch_ten_times():
session = requests.Session()
tasks = [
fetch(session),
fetch(session),
fetch(session),
fetch(session),
fetch(session),
fetch(session),
fetch(session),
fetch(session),
fetch(session),
fetch(session),
]
session.close()
async def fetch_async(session):
resp = await session.get("https://github.com/fwkoch")
print(resp.status)
return resp.status
async def fetch_async_ten_times():
session = aiohttp.ClientSession()
tasks = await asyncio.gather(
fetch_async(session),
fetch_async(session),
fetch_async(session),
fetch_async(session),
fetch_async(session),
fetch_async(session),
fetch_async(session),
fetch_async(session),
fetch_async(session),
fetch_async(session),
)
await session.close()
if __name__ == "__main__":
start = time.time()
fetch_ten_times()
print(f"Elapsed time: {time.time() - start}")
start = time.time()
asyncio.run(fetch_async_ten_times())
print(f"Elapsed time: {time.time() - start}")