python requests response time

Python Requests Response Time

When working with web APIs, it's important to consider the response time of our requests. Python's Requests library makes it easy to make HTTP requests in Python. Here are some ways to measure the response time of a request using Python Requests.

Using the elapsed property

The simplest way to measure the response time of a request is to use the elapsed property of the Response object returned by requests.get(). The elapsed property returns a timedelta object representing the time taken for the request to complete.


import requests

response = requests.get('https://api.example.com')
print(response.elapsed.total_seconds())

The above code will print the number of seconds it took for the request to complete. Note that this includes the time taken for DNS resolution, TCP handshake, and SSL negotiation (if applicable).

Using the time module

If you want more control over the timing of your requests, you can use the time module to measure the time taken for a request to complete.


import requests
import time

start_time = time.time()
response = requests.get('https://api.example.com')
end_time = time.time()

print(end_time - start_time)

The above code measures the time taken for the request to complete using time.time() to get the start and end times. Note that this method does not include the time taken for DNS resolution, TCP handshake and SSL negotiation.

Using the requests_toolbelt library

The requests_toolbelt library provides a TimerSession that can be used to automatically measure the time taken for a request to complete.


from requests_toolbelt import TimedSession

session = TimedSession()
response = session.get('https://api.example.com')
print(response.elapsed.total_seconds())

The above code uses a TimedSession object to make the request. The elapsed property of the Response object returned by the TimedSession object contains the time taken for the request to complete.

These are some of the ways to measure the response time of a request using Python Requests. It's important to consider the response time of requests when building applications that rely on web APIs.