When working with APIs or monitoring server performance, it's often important to measure how long a POST request takes in Python. Python's requests library provides a few simple and accurate ways to do this.

1. Use response.elapsed (Simplest)

The easiest way is to use the built-in elapsed attribute:

import requests

response = requests.post("https://httpbin.org/post", data={"key": "value"})
print(response.elapsed.total_seconds())

result:

0.521439

This measures the time between sending the request and receiving the response headers. It's simple and good for most use cases.

2. Use time.perf_counter() for Full Timing

For more precise control (including DNS, connection, and full body transfer), wrap the call with a timer:

import time
import requests

start = time.perf_counter()
response = requests.post("https://httpbin.org/post", data={"key": "value"})
end = time.perf_counter()

print(f"Total time: {end - start:.4f} seconds")

output is:

Total time: 0.8161 seconds

This measures the full round-trip time more accurately.

3. Use timeout to Control Long Requests

While not a timer, setting a timeout prevents hanging requests:

response = requests.post(
    "https://httpbin.org/post",
    data={"key": "value"},
    timeout=5
)

This ensures your script fails fast if the server is slow.

For more info on this check: How To Send Request with Timeout Parameter in Python