Created
April 10, 2023 05:10
-
-
Save taesiri/6ea37c7678cc2dec99ed2b7755f53d88 to your computer and use it in GitHub Desktop.
SpeedTest.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import time | |
def format_speed(speed_bytes): | |
""" | |
Formats download speed into a human-readable string. | |
:param speed_bytes: Download speed in bytes per second | |
:return: Formatted download speed string | |
""" | |
if speed_bytes < 1024: | |
return f"{speed_bytes:.2f} bytes/s" | |
elif speed_bytes < 1024**2: | |
return f"{speed_bytes / 1024:.2f} KB/s" | |
elif speed_bytes < 1024**3: | |
return f"{speed_bytes / (1024 ** 2):.2f} MB/s" | |
else: | |
return f"{speed_bytes / (1024 ** 3):.2f} GB/s" | |
def compare_proxy_speed(url, proxy=None, timeout=10): | |
""" | |
Compares download speeds with and without a proxy. | |
:param url: URL of the file to be downloaded | |
:param proxy: Proxy URL (e.g., 'http://user:password@proxy.example.com:8080'), default is None | |
:param timeout: Timeout for the download request, default is 10 seconds | |
:return: Tuple containing download speeds without proxy and with proxy in human-readable format | |
""" | |
def download(url, proxies, timeout): | |
start_time = time.time() | |
try: | |
response = requests.get(url, proxies=proxies, timeout=timeout) | |
response.raise_for_status() | |
end_time = time.time() | |
elapsed_time = end_time - start_time | |
download_speed = len(response.content) / elapsed_time | |
return format_speed(download_speed) | |
except requests.exceptions.RequestException as e: | |
print(f"Error downloading file: {e}") | |
return None | |
no_proxy_speed = download(url, None, timeout) | |
proxy_speed = download(url, {"http": proxy, "https": proxy}, timeout) | |
if no_proxy_speed and proxy_speed: | |
print(f"Download speed without proxy: {no_proxy_speed}") | |
print(f"Download speed with proxy: {proxy_speed}") | |
elif no_proxy_speed: | |
print(f"Download speed without proxy: {no_proxy_speed}") | |
print("Could not estimate download speed with proxy.") | |
elif proxy_speed: | |
print("Could not estimate download speed without proxy.") | |
print(f"Download speed with proxy: {proxy_speed}") | |
else: | |
print("Could not estimate download speeds.") | |
return no_proxy_speed, proxy_speed | |
# Example usage | |
url = "http://cachefly.cachefly.net/10mb.test" | |
proxy = "http://@localhost:2000" | |
no_proxy_speed, proxy_speed = compare_proxy_speed(url, proxy) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment