Before proceeding, please ensure that you have the right to perform this kind of request load against the target server. Unauthorized or malicious use of such scripts can violate laws and terms of service, leading to serious consequences.
Assuming you have legitimate reasons (e.g., load testing your own server), here are several optimizations to make your asynchronous script faster:
-
Use uvloop for a Faster Event Loop:
uvloop is a high-performance event loop implementation for Python's asyncio that can significantly speed up your asynchronous code.
-
Optimize Semaphore Usage:
Utilizing both a high semaphore limit and a high connector limit can lead to excessive resource consumption. It’s often better to let the connector manage concurrency.
-
Reuse Request Data:
Prepare your request data and headers beforehand to avoid recreating them for every request.
-
Ensure Efficient Encoding:
Send your data as bytes to prevent implicit encoding during each request.
-
Handle Exceptions Gracefully:
Instead of printing exceptions, consider using logging for better performance and control.
-
Adjust System Resources:
Ensure that your system's file descriptor limits and network settings can handle the increased number of concurrent connections.
Here's the optimized script incorporating these improvements:
import asyncio
import aiohttp
import time
import uvloop
import logging
# Set up uvloop for better performance
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
# Configure logging
logging.basicConfig(level=logging.ERROR) # Change to INFO or DEBUG for more details
logger = logging.getLogger(__name__)
async def make_request(session, url, data, headers):
try:
async with session.post(url, data=data, headers=headers) as response:
await response.read() # Ensure the response is consumed
except Exception as e:
logger.error(f"Request failed: {e}")
async def main():
url = "https://secret-share.net/play/action.php"
data = b"username=test" # Send data as bytes for efficiency
headers = {
"accept": "*/*",
"accept-language": "en-US,en;q=0.9,ru;q=0.8",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"cookie": "PHPSESSID=em2m7stql0nuotbosbapm3cmbr", # Replace with your actual session ID
"origin": "https://secret-share.net",
"priority": "u=1, i",
"referer": "https://secret-share.net/play/",
"sec-ch-ua": "\"Chromium\";v=\"130\", \"Google Chrome\";v=\"130\", \"Not?A_Brand\";v=\"99\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Windows\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 "
"Safari/537.36",
"x-requested-with": "XMLHttpRequest"
}
# Configure the connector with optimized limits
connector = aiohttp.TCPConnector(
limit=1000, # Total concurrent connections
limit_per_host=1000, # Concurrent connections per host
ttl_dns_cache=300 # DNS cache duration
)
# Optionally, adjust your semaphore based on system capabilities
semaphore = asyncio.Semaphore(1000)
async with aiohttp.ClientSession(connector=connector) as session:
tasks = []
start_time = time.time()
# Prepare tasks without unnecessary semaphore if connector limits suffice
for _ in range(1000):
task = asyncio.create_task(make_request(session, url, data, headers))
tasks.append(task)
# Use asyncio.gather to run all tasks concurrently
await asyncio.gather(*tasks, return_exceptions=True)
end_time = time.time()
print(f"1000 requests completed in {end_time - start_time:.2f} seconds")
# Close the connector explicitly (optional, as ClientSession does it)
await connector.close()
if __name__ == "__main__":
asyncio.run(main())
Explanation of Optimizations
-
Using uvloop:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
uvloop can provide up to 2-3 times speed improvements over the default event loop in many cases.
-
Efficient Data Handling:
data = b"username=test" # Use bytes instead of string
Sending data as bytes avoids the overhead of encoding strings to bytes during each request.
-
Optimized Connector Configuration:
connector = aiohttp.TCPConnector(
limit=1000,
limit_per_host=1000,
ttl_dns_cache=300
)
limit: Maximum number of concurrent connections.
limit_per_host: Maximum concurrent connections per host.
ttl_dns_cache: Time-to-live for DNS cache to reduce DNS lookup overhead.
-
Logging Instead of Printing:
import logging
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger(__name__)
...
logger.error(f"Request failed: {e}")
Logging is more efficient and manageable than printing, especially when handling many exceptions.
-
Removing Unnecessary Semaphore:
If the TCPConnector limits concurrency effectively, an additional semaphore might be redundant. However, if you still need to control concurrency due to system limitations, you can reintroduce it with a lower value.
-
Consuming the Response Properly:
await response.read()
Ensures that the connection is released back to the pool promptly.
-
Explicitly Closing the Connector:
While the ClientSession context manager handles this, explicitly closing the connector can help free resources faster in some scenarios.
Additional Tips
-
System Limits: Ensure that your operating system allows a high number of open file descriptors. On Unix-like systems, you can check and set this with:
ulimit -n 10000
-
Network Bandwidth: Ensure that your network can handle the increased number of concurrent requests without throttling.
-
Error Handling: Implement more sophisticated error handling if necessary, such as retries with exponential backoff for transient errors.
-
Batching Requests: If sending all requests at once overwhelms your system or the target server, consider sending them in smaller batches with controlled delays.
Using aiohttp Efficiently
aiohttp is already optimized for high concurrency, but here are some best practices to maximize performance:
-
Reuse Sessions: Opening a new session for each request is costly. Reusing a single ClientSession is essential for performance.
-
Keep Connections Alive: aiohttp handles persistent connections by default with ClientSession, reducing the overhead of establishing new connections.
-
DNS Caching: Caching DNS lookups with ttl_dns_cache reduces latency for subsequent requests to the same host.
By implementing these optimizations, you should see improved performance in your asynchronous requests. Always monitor your application's resource usage to ensure that it operates within your system's capabilities.