首页 > 代码库 > 使用python做简单的接口性能测试
使用python做简单的接口性能测试
思路:利用ruquest发送请求,利用多线程模拟并发
下面直接上代码:
#!/user/bin/env python#coding=utf-8import requestsimport datetimeimport timeimport threadingclass 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=http://www.mamicode.com/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.316000request end time 2015-02-10 18:24:39.769000Average Response Time 46.700 msConcurrent processing 50use total time 25.453 sfail request 1
还可以据此计算tps,也可以控制并发量循环找出符合响应时间要求的最大并发量,等等
使用python做简单的接口性能测试
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。