Skip to content

Commit 8395d24

Browse files
committed
Asyncio\06-get-site-data-sync-vs-async
1 parent 2323e43 commit 8395d24

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import asyncio
2+
import time
3+
import urllib
4+
import aiohttp
5+
6+
URL = "https://www.python.org/"
7+
COUNTER_REQUEST = 10
8+
9+
def get_site_data_syn(request_number):
10+
print(f"Synchronous request {request_number}")
11+
start = time.perf_counter()
12+
response = urllib.request.urlopen(URL)
13+
datetime = response.getheader('Date')
14+
print(f"Synchronous request {request_number} Finished ==> {datetime}, {time.perf_counter()-start}")
15+
return datetime
16+
17+
18+
async def aiohttp_get(url):
19+
async with aiohttp.ClientSession() as session:
20+
async with session.get(url) as response:
21+
return response
22+
23+
24+
async def get_site_data_async(request_number):
25+
print(f"Asynchronous request {request_number}")
26+
start = time.perf_counter()
27+
response = await aiohttp_get(URL)
28+
datetime = response.headers.get('Date')
29+
print(f"Asynchronous request {request_number} Finished ==> {datetime}, {time.perf_counter()-start}")
30+
response.close()
31+
return datetime
32+
33+
34+
def synchronous():
35+
start = time.perf_counter()
36+
for i in range(COUNTER_REQUEST):
37+
get_site_data_syn(i)
38+
print(f"Execution time (synchronous) : {time.perf_counter()-start}")
39+
40+
41+
async def asynchronous():
42+
start = time.perf_counter()
43+
tasks = [asyncio.create_task(get_site_data_async(i)) for i in range(COUNTER_REQUEST)]
44+
for task in tasks:
45+
await task
46+
print(f"Execution time (asynchronous) : {time.perf_counter()-start}")
47+
48+
49+
synchronous()
50+
asyncio.run(asynchronous())

0 commit comments

Comments
 (0)