Skip to content

Instantly share code, notes, and snippets.

@harshildarji
Created August 19, 2023 14:59
Show Gist options
  • Save harshildarji/db8d6bd67b6330b3038b0a8bc84751a8 to your computer and use it in GitHub Desktop.
Save harshildarji/db8d6bd67b6330b3038b0a8bc84751a8 to your computer and use it in GitHub Desktop.
import csv
from datetime import datetime
import speedtest
def measure_speed():
st = speedtest.Speedtest(secure=True)
st.get_best_server() # This will select the best server based on ping
download_speed = st.download() / 1_000_000 # Convert to MBit/s
upload_speed = st.upload() / 1_000_000 # Convert to MBit/s
ping = st.results.ping
server_name = st.results.server["name"]
server_location = st.results.server["sponsor"] + ", " + st.results.server["country"]
return download_speed, upload_speed, ping, server_name, server_location
def store_speed(download_speed, upload_speed, ping, server_name, server_location):
with open(
"/Users/harshil/Desktop/internet/internet_speeds.csv", "a", newline=""
) as file:
writer = csv.writer(file)
writer.writerow(
[
datetime.now(),
download_speed,
upload_speed,
ping,
server_name,
server_location,
]
)
def main():
# Check if the file exists, if not, create and add headers
try:
with open("/Users/harshil/Desktop/internet/internet_speeds.csv", "r") as file:
pass
except FileNotFoundError:
with open(
"/Users/harshil/Desktop/internet/internet_speeds.csv", "w", newline=""
) as file:
writer = csv.writer(file)
writer.writerow(
[
"Timestamp",
"Download Speed (MBit/s)",
"Upload Speed (MBit/s)",
"Ping (ms)",
"Server Name",
"Server Location",
]
)
download_speed, upload_speed, ping, server_name, server_location = measure_speed()
store_speed(download_speed, upload_speed, ping, server_name, server_location)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment