Skip to content

Commit 4058d06

Browse files
Create LatencyThroughput.py
In this code, we use the with statement to create a Session object for each function. This allows us to reuse the underlying TCP connection between requests, which can reduce the overhead associated with establishing a new connection for each request. We also updated the requests.get() calls to use session.get() instead. Note that the impact of using a Session object may vary depending on the specific API endpoint and network conditions involved, so it's a good idea to test the performance of the script with and without a Session object to determine if it provides any benefit.
1 parent db532c6 commit 4058d06

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

LatencyThroughput.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import requests
2+
import time
3+
4+
API_ENDPOINT = "https://api.example.com"
5+
6+
# def measure_latency():
7+
# latencies = []
8+
# for i in range(10):
9+
# start_time = time.time()
10+
# response = requests.get(API_ENDPOINT)
11+
# end_time = time.time()
12+
# latency = end_time - start_time
13+
# latencies.append(latency)
14+
# print(f"Request {i+1}: {latency:.4f} seconds")
15+
# average_latency = sum(latencies) / len(latencies)
16+
# print(f"Average latency: {average_latency:.4f} seconds")
17+
18+
19+
def measure_latency():
20+
latencies = []
21+
with requests.Session() as session:
22+
for i in range(10):
23+
start_time = time.time()
24+
response = session.get(API_ENDPOINT)
25+
end_time = time.time()
26+
latency = end_time - start_time
27+
latencies.append(latency)
28+
print(f"Request {i+1}: {latency:.4f} seconds")
29+
average_latency = sum(latencies) / len(latencies)
30+
print(f"Average latency: {average_latency:.4f} seconds")
31+
32+
33+
def measure_throughput():
34+
with requests.Session() as session:
35+
start_time = time.time()
36+
for i in range(10):
37+
response = session.get(API_ENDPOINT)
38+
end_time = time.time()
39+
total_time = end_time - start_time
40+
throughput = 10 / total_time
41+
print(f"Throughput: {throughput:.2f} requests/second")
42+
43+
measure_latency()
44+
measure_throughput()

0 commit comments

Comments
 (0)