python requests elapsed milliseconds

Python Requests Elapsed Milliseconds

If you are working in Python and using the Requests library to send HTTP requests, you may want to measure the elapsed time it takes for each request to complete. There are a few ways to do this, but one common approach is to use the built-in Python time module.

Using the Time Module

To measure the elapsed time for a request, we can use the time.time() function from the time module. This function returns the current time in seconds since the Epoch (January 1, 1970, 00:00:00 UTC).

To use this function, we can record the start time before sending the request and then record the end time after receiving the response. We can then subtract the start time from the end time to get the elapsed time in seconds.


import requests
import time

# Record start time
start_time = time.time()

# Send request
response = requests.get('https://www.example.com')

# Record end time
end_time = time.time()

# Calculate elapsed time in milliseconds
elapsed_time_ms = (end_time - start_time) * 1000

print(f'Response took {elapsed_time_ms:.2f} milliseconds')

In this example, we are sending a GET request to https://www.example.com and measuring the elapsed time in milliseconds. We use string formatting to print out the elapsed time with two decimal places.

Using the Requests Library

The Requests library also provides a way to measure the elapsed time for a request using a built-in timer. You can access this timer through the elapsed attribute of the response object.


import requests

# Send request
response = requests.get('https://www.example.com')

# Get elapsed time in milliseconds
elapsed_time_ms = response.elapsed.total_seconds() * 1000

print(f'Response took {elapsed_time_ms:.2f} milliseconds')

In this example, we are sending a GET request to https://www.example.com and using the elapsed attribute to get the elapsed time in milliseconds. We use string formatting to print out the elapsed time with two decimal places.

Both of these approaches will give you the elapsed time for a request in milliseconds. Choose the one that works best for your particular use case.