[英]How to measure the number and response time of GET requests a backend can handle in a given time using Python?
我正在嘗試測量我在本地運行的后端處理 GET 請求的速度。
為了衡量這一點,我計划使用發送請求的 Python 腳本。 理想情況下,我想在給定時間(比如 10 秒)內盡可能快地發送盡可能多的請求,然后計算在該時間內返回的所有響應,但不計算稍后到達的響應。 此外,我想測量每個單獨請求的響應時間,即發送請求和響應到達之間的時間。
我的第一次嘗試是這樣的:
async def scalability_test(seconds):
serviced = 0
total_response_time_micro = 0
timeout = time.time() + seconds
async with aiohttp.ClientSession() as session:
while time.time() < timeout:
async with session.get(url=BASE_URL + str(serviced + 1)) as resp:
time_before = datetime.datetime.now()
dummy = await resp.json()
print(dummy)
response_time_micro = (datetime.datetime.now().microsecond - time_before.microsecond)
print("This took " + str(response_time_micro) + " microseconds.")
total_response_time_micro += response_time_micro
serviced += 1
print("Number of requests serviced in " + str(seconds) + " seconds: " + str(serviced) + ".")
print("In total, the response time was " + str(total_response_time_micro) + " microseconds.")
print("On average, responses took " + str(total_response_time_micro / serviced) + " microseconds.")
這給了我一個實際數量的服務請求,但我不確定它是否成功發送了所有請求,或者只是那些及時返回的請求。 此外,每個單獨請求的響應時間似乎很短,所以我認為我在計時方面做錯了。
我的問題是完全異步運行它似乎很難測量時間(不可能?),但如果我等待一切,它只會變成同步 function。
我問的是可能的嗎? 任何幫助將不勝感激。
也許另一種增加負載的方法是使用 multiprocessing.Pool 來確保您運行同一個 function 的多個並行線程。
from multiprocessing import Pool
if __name__ == '__main__':
with Pool(5) as p: # 5 is the number of threads you want to launch, prefer a number close to you actual processor number of threads
p.map(scalability_test, [seconds_1, seconds_2, seconds_3]) # this should launch one job for each member of [second...] so in your case you can use at least one per thread
但是,要測量時間,我認為您必須使用回調而不是在每次調用時阻塞線程。 我不知道如何使用 aiohttp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.