-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasyncio.py
More file actions
81 lines (66 loc) · 2.21 KB
/
Copy pathasyncio.py
File metadata and controls
81 lines (66 loc) · 2.21 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
import asyncio
import os
import time
from pathlib import Path
from tempfile import gettempdir
from aiofile import async_open, FileIOWrapperBase
import aiohttp
from lib import (
generate_valid_urls,
get_dir_name,
get_openable_fd_for_req,
raise_fd_limit
)
from runner import program_runner
async def get_and_write_data(
url:str,
client: aiohttp.ClientSession,
af:FileIOWrapperBase
):
try:
async with client.get(url) as response:
if not response.ok:
print(response.status)
return False
await af.write(await response.read())
except Exception as e:
print(repr(e))
return False
else:
return True
async def main(url_count=50):
tmp_filenam = Path(gettempdir()) / "data"
failed_count = 0
total_bytes = 0
tcp_connector = aiohttp.TCPConnector(
limit=get_openable_fd_for_req(),
ttl_dns_cache=60*60*10
)
async with async_open(tmp_filenam, "ab+") as af:
async with aiohttp.ClientSession(connector=tcp_connector) as client:
results = await asyncio.gather(
*[
get_and_write_data(url, client, af)
for url in generate_valid_urls(url_count)
]
)
failed_count = url_count - sum(results)
await af.flush()
total_bytes = os.stat(tmp_filenam).st_size
os.unlink(tmp_filenam)
return total_bytes, failed_count
if __name__ == "__main__":
raised = raise_fd_limit()
print("Raised fd limit", raised)
def execute(url_count=100_000):
return asyncio.run(main(url_count))
for count in [10_000, 100_000]:
print("Execution for:", count, "urls")
program_runner(
execute,
f"asyncio_data_with_{count}_urls",
get_dir_name(__file__),
url_count=count,
descr=f"""Io bound execution using asyncio programming. The experiment fetches {count} urls and stores the response data into a file. The returned values represnt the total bytes received from network and the number of failed requests (>=400 status code or error)."""
)
time.sleep(10)