2 min read

Basic Website Speed Test

This utility measures the response time of a website. It calculates the Time to First Byte (TTFB), which is the time it takes for the server to start sending data, and the total time taken to download the full page content.

Modules Used:

  • requests: To make HTTP requests.
  • argparse: To handle command-line arguments.
  • time: To measure execution time.

The Code

Save this as site_speed.py.

import requests
import time
import argparse

def test_website_speed(url):
    print(f"Testing speed for: {url}")

    try:
        # Start timer
        start_time = time.time()

        # Make request
        # stream=True allows us to measure TTFB separately from content download
        # We use a custom user agent to avoid being blocked by some servers
        headers = {'User-Agent': 'Python Speed Tester 1.0'}
        response = requests.get(url, stream=True, timeout=10, headers=headers)

        # Time to First Byte (TTFB)
        # This is roughly the time it took for the server to start sending data
        ttfb = time.time() - start_time

        # Read content to measure download time
        # We don't need to do anything with the content, just consume it to measure throughput
        size_bytes = 0
        for chunk in response.iter_content(chunk_size=8192):
            size_bytes += len(chunk)

        end_time = time.time()
        total_time = end_time - start_time
        download_time = total_time - ttfb

        size_kb = size_bytes / 1024

        print(f"\nStatus Code: {response.status_code}")

        print("-" * 40)
        print(f"Time to First Byte (TTFB): {ttfb:.4f}s")
        print(f"Download Time:             {download_time:.4f}s")
        print(f"Total Request Time:        {total_time:.4f}s")
        print(f"Page Size:                 {size_kb:.2f} KB")
        if total_time > 0:
            print(f"Avg Speed:                 {size_kb / total_time:.2f} KB/s")
        print("-" * 40)

    except requests.exceptions.Timeout:
        print("Error: Request timed out.")
    except requests.exceptions.ConnectionError:
        print("Error: Could not connect to the server.")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Basic Website Speed Test")
    parser.add_argument("url", help="URL of the website to test")

    args = parser.parse_args()

    url = args.url
    if not url.startswith("http"):
        url = "https://" + url

    test_website_speed(url)

Usage

python site_speed.py google.com

programming/python/python