Speed Up Your Website: Measuring Page Load Times in Python

Feb 3, 2024 ยท 2 min read

Have you ever visited a website and it felt slow to load? As a developer, being able to measure page load times is crucial for providing a good user experience. Python makes this easy with the requests module.

In this article, I'll walk through a simple script to fetch a webpage and calculate how long it takes to fully load.

Fetching a Page with Requests

First, we need to install requests:

pip install requests

Then we can fetch a page. Let's try example.com:

import requests

response = requests.get('https://example.com')

This sends a GET request to the URL and saves the Response object to response.

Timing Page Load

Now we can use Python's time module to measure how long the request took:

import time
start_time = time.time()  

response = requests.get('https://example.com')

end_time = time.time()
duration = end_time - start_time

print(f"Page loaded in {duration} seconds")

We record the start time before making the request, and the end time after. By subtracting them, we get the total duration.

On my machine, example.com loaded in 0.58 seconds. That's pretty fast!

Going Further

There's a lot more we could do:

  • Test multiple URLs
  • Break timing into DNS lookup, connection, etc
  • Compare page size impact
  • Track over time and set performance budgets
  • Measuring page load times helps find performance issues. Slow sites lead to unhappy users, so keep your pages speedy!

    Browse by tags:

    Browse by language:

    Tired of getting blocked while scraping the web?

    ProxiesAPI handles headless browsers and rotates proxies for you.
    Get access to 1,000 free API credits, no credit card required!