Complete the code to measure the latency of a function call.
import time start = time.[1]() result = my_function() end = time.perf_counter() latency = end - start print(f"Latency: {latency} seconds")
We use time.perf_counter() because it provides the highest available resolution timer to measure short durations accurately.
Complete the code to calculate the average cost per API call given total cost and number of calls.
total_cost = 50.0 # dollars num_calls = 200 average_cost = total_cost [1] num_calls print(f"Average cost per call: ${average_cost:.4f}")
To find the average cost per call, divide the total cost by the number of calls.
Fix the error in the code to correctly record the latency of multiple runs and compute the average latency.
import time latencies = [] for _ in range(5): start = time.perf_counter() run_task() end = time.[1]() latencies.append(end - start) avg_latency = sum(latencies) / len(latencies) print(f"Average latency: {avg_latency:.5f} seconds")
The end timer must match the start timer function perf_counter() to measure elapsed time correctly.
Fill both blanks to create a dictionary of API call latencies filtered by calls longer than 0.1 seconds.
latency_data = {call_id: [1] for call_id, [2] in api_calls.items() if latency > 0.1}The dictionary comprehension uses latency as the value and duration as the variable for each call's time.
Fill all three blanks to create a filtered dictionary of call costs where cost is above 0.05 dollars and keys are uppercase.
filtered_costs = [1]([2]: cost for [3], cost in call_costs.items() if cost > 0.05)
The dictionary is created with dict(), keys converted to uppercase with k.upper(), and iterating over keys k and values cost.