除了使用性能測試工具進行性能測試,咱們也能夠直接用python多線程進行性能測試。html
下面,使用這幾個模塊,對一個查詢接口作性能測試:python
requests:發送http請求json
json:返回的字符串轉換成json格式api
threading:多線程多線程
time:統計時間app
具體實現過程見代碼及註釋。工具
import requests import json import threading import time # 定義請求基本地址 base_url = "http://127.0.0.1:8000" success = 0 fail = 0 # 查詢線程 def get_guest_list_thread(start_user,end_user): for i in range(start_user,end_user): phone = 13800138000 + i r = requests.get(base_url+'/api/get_guest_list/', params={'eid':1,'phone':phone}) # print(r.status_code) # 200 # print(r.content) # b'{"status": 200, "message": "success", "data": {"realname": "alen", "phone": "13800138000", "email": "alen@mail.com", "sign": false}}' # print(r.json()) # {'status': 200, 'message': 'success', 'data': {'realname': 'alen', 'phone': '13800138000', 'email': 'alen@mail.com', 'sign': False}} # print(type(r)) # <class 'requests.models.Response'> ,這個類型有json方法,不須要import json # print(r) # <Response [200]> # print(json.loads(r.content)) #須要import json,{'status': 200, 'message': 'success', 'data': {'realname': 'alen', 'phone': '13800138000', 'email': 'alen@mail.com', 'sign': False}} result = r.json() global success,fail try: if phone=='13800138000' or phone=='13800138001': assert result['status'] == 20 success +=1 else: assert result['status'] == 10022 success +=1 except AssertionError as e: print('get error:'+str(phone)) fail +=1 # 5個線程,25個數據 # lists = {1:6, 6:11, 11:16, 16:21, 21:26} # 能夠這樣寫數據,也能夠經過下面生成 data = 25 n = 5 step = int(data/n) lists = {} for i in range(1,n+1): lists[(i-1)*step+1]=i*step + 1 print(lists) # 建立線程列表 threads = [] # 建立線程 for start_user,end_user in lists.items(): t = threading.Thread(target=get_guest_list_thread,args=(start_user,end_user)) # args是一個元組 threads.append(t) if __name__ == '__main__': # 開始時間 start_time = time.time() # 啓動線程 for i in range(len(lists)): threads[i].start() for i in range(len(lists)): threads[i].join() # 結束時間 time.sleep(3) # 爲了更明顯看出用例執行耗時,加上休眠 end_time = time.time() print("開始時間:"+str(start_time)+'>>>>>'+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(start_time))) print("結束時間:"+str(end_time)+'>>>>>'+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(end_time))) print('總共耗時:' + str(end_time - start_time)) print('總共耗時:%.2f'%(end_time - start_time)) # 保留兩位小數 print('測試經過用例數:{}, 測試失敗用例數:{}, 測試經過率爲:{}'.format(success,fail,str(success*100/(success+fail))+'%'))
結果:性能