Python3接口性能測試實例代碼

首先來看實例代碼:

# -*- coding:utf-8 -*-


import requests
import datetime
import time
import threading

'''
allow_redirects = False禁止重定向,添加在request參數後
get請求用params傳參
post請求,數據類型form,用data傳參
post請求,數據類型form,用data傳參
post請求,數據類型json,json傳參
timeout:請求超時時間,添加在request參數後
nub = 10#設置並發線程數
ResponseTime=float(result.elapsed.microseconds)/1000 #獲取響應時間,單位ms
ThinkTime = 0.5#設置思考時間
AverageTime = "{:.3f}".format(float(sum(myrequest.times))/float(len(myrequest.times)))#計算數組的平均值,保留3位小數
totaltime = float(hour)*60*60 + float(minute)*60 + float(second) #計算總的思考時間+請求時間
'''

class url_request:
    times = []
    error = []
    def weather_DC(self):
        myrequest=url_request()
        weatherinfo_search = 'https://restapi.amap.com/v3/weather/weatherInfo?parameters'
        params = {'key': 'cd1b11e80ffac05253196aa2a1233f25',
                  'city': 110101,
                  'extensions': 'base',
                  'output': 'JSON'}

        result = requests.get(url=weatherinfo_search, params=params)
        print("狀態碼:",result.status_code)
        print("返回報文:",result.text)
        ResponseTime=float(result.elapsed.microseconds)/1000
        myrequest.times.append(ResponseTime)
        if result.status_code !=200 :
            myrequest.error.append("0")
if __name__=='__main__':
    myrequest=url_request()
    threads = []
    starttime = datetime.datetime.now()
    print("請求開始時間:request start time %s" %starttime)
    nub = 10
    ThinkTime = 0.5
    for i in range(1, nub+1):
        t = threading.Thread(target=myrequest.weather_DC())
        threads.append(t)
    for t in threads:
        time.sleep(ThinkTime)
        print("線程數:thread %s" %t)
        t.setDaemon(True)
        t.start()
        t.join()
    endtime = datetime.datetime.now()
    print("請求結束時間:request end time %s" %endtime)
    time.sleep(3)
    AverageTime = "{:.3f}".format(float(sum(myrequest.times))/float(len(myrequest.times)))
    print("平均響應時間:Average Response Time %s ms" %AverageTime)
    usetime = str(endtime - starttime)
    hour = usetime.split(':').pop(0)
    minute = usetime.split(':').pop(1)
    second = usetime.split(':').pop(2)
    totaltime = float(hour)*60*60 + float(minute)*60 + float(second)
    print("並發數:Concurrent processing %s" %nub)
    print("#總共消耗的時間:use total time %s s" %(totaltime-float(nub*ThinkTime)))
    print("錯誤請求數:fail request %s s" %myrequest.error.count("0"))

實例擴展:

利用ruquest發送請求,利用多線程模擬並發

#!/user/bin/env python
#coding=utf-8
import requests
import datetime
import time
import threading

class url_request():
    times = []
    error = []
    def req(self,AppID,url):
        myreq=url_request()
        headers = {'User-Agent' : 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19'}
        payload = {'AppID':AppID,'CurrentURL':url}
        r = requests.post("http://xx.xxx.com/WeiXinJSAccessToken/json/WeChatJSTicket",headers=headers,data=payload)
        ResponseTime=float(r.elapsed.microseconds)/1000 #獲取響應時間,單位ms
        myreq.times.append(ResponseTime) #將響應時間寫入數組
        if r.status_code !=200 :
            myreq.error.append("0")
if __name__=='__main__':
    myreq=url_request()
    threads = []
    starttime = datetime.datetime.now()
    print "request start time %s" %starttime 
    nub = 50#設置並發線程數
    ThinkTime = 0.5#設置思考時間
    for i in range(1, nub+1): 
        t = threading.Thread(target=myreq.req, args=('12','http://m.ctrip.com/webapp/cpage/#mypoints'))
        threads.append(t)
    for t in threads:
        time.sleep(ThinkTime) 
        #print "thread %s" %t #打印線程
        t.setDaemon(True)
        t.start()
    t.join()
    endtime = datetime.datetime.now()
    print "request end time %s" %endtime  
    time.sleep(3)
    AverageTime = "{:.3f}".format(float(sum(myreq.times))/float(len(myreq.times))) #計算數組的平均值,保留3位小數
    print "Average Response Time %s ms" %AverageTime #打印平均響應時間
    usetime = str(endtime - starttime)
    hour = usetime.split(':').pop(0)
    minute = usetime.split(':').pop(1)
    second = usetime.split(':').pop(2)
    totaltime = float(hour)*60*60 + float(minute)*60 + float(second) #計算總的思考時間+請求時間
    print "Concurrent processing %s" %nub #打印並發數
    print "use total time %s s" %(totaltime-float(nub*ThinkTime)) #打印總共消耗的時間
    print "fail request %s" %myreq.error.count("0") #打印錯誤請求數
request start time 2015-02-10 18:24:14.316000
request end time 2015-02-10 18:24:39.769000
Average Response Time 46.700 ms
Concurrent processing 50
use total time 25.453 s
fail request 1

到此這篇關於Python3接口性能測試實例代碼的文章就介紹到這瞭,更多相關Python3實現簡單的接口性能測試內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: