import requests
import datetime
import time
import threading
class url_request():
times = []
error = []
def req(self):
myreq=url_request()
headers = {
'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
'Referer': 'http://test.m.ncfimg.com/',
'XHTK':'pnzwrw1atkdms11ze5sj1ttkpbl1d6l0tn'
}
r = requests.post("http://test.api.ncfimg.com/nmvapi/index/index",headers=headers)
ResponseTime=float(r.elapsed.total_seconds())*1000
myreq.times.append(ResponseTime)
if r.status_code !=200 :
myreq.error.append("0")
with open('threads_result','a') as f:
f=f.write(str(r.status_code)+'\n')
print(ResponseTime)
class Thread_out():
def __init__(self):
global nub
nub=1
def threads(self):
myreq = url_request()
threads = []
starttime = datetime.datetime.now()
print("请求开始时间: %s" % starttime)
ThinkTime = 0
for i in range(1, nub + 1):
t = threading.Thread(target=myreq.req, args=())
threads.append(t)
for t in threads:
time.sleep(ThinkTime)
t.setDaemon(True)
t.start()
t.join()
endtime = datetime.datetime.now()
print("请求结束时间: %s" % endtime)
time.sleep(0)
AverageTime = "{:.3f}".format(float(sum(myreq.times)) / float(len(myreq.times)))
print("平均响应时间: %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("并发数量: %s" % nub)
print("总消耗时间: %s s" % (totaltime - float(nub * ThinkTime)))
print("错误请求数: %s" % myreq.error.count("0"))
if __name__=='__main__':
t=Thread_out()
t.threads()