#coding =utf-8
Import Urllib2
Import threading
Import time
Total = 0 #总数
SUCC = 0 #响应成功数
FAIL = 0 #响应失败数
EXCEPT = 0 #响应异常数
Maxtime=0 #最大响应时间
Mintime=100 #最小响应时间 with an initial value of 100 seconds
# Sub-class thread
Class Mythread (threading. Thread):
def __init__ (self, func, args, name= "):
Threading. Thread.__init__ (self)
Self.name = Name
Self.func = Func
Self.args = args
def getresult (self):
Return Self.res
def run (self):
Self.res = Apply (Self.func, Self.args)
def request_url (URL, R):
Global Total
Global SUCC
Global FAIL
Global EXCEPT
Try
st = Time.time ()
res = urllib2.urlopen (URL)
Status = Res.getcode ()
If status = = 200:
Total+=1
Succ+=1
Else
Total+=1
Fail+=1
Time_span = Time.time ()-st
MaxTime (Time_span)
Self.mintime (Time_span)
Except Exception, E:
Total+=1
Except+=1
def maxtime (TS):
Global MaxTime
If Ts>maxtime:
Maxtime=ts
def mintime (TS):
Global Mintime
If Ts<mintime:
Mintime=ts
def main ():
print ' ===========task start=========== '
# Time to start
Start_time = Time.time ()
# Number of concurrent threads
Thread_count = 100
i = 0
While I <= Thread_count:
t = Mythread (Request_url, ("http://www.baidu.com", "X"))
T.start ()
i + = 1
T=0
#并发数所有都完成或大于20秒就结束
While total<thread_count|t>2:
Print "total:%d,succ:%d,fail:%d,except:%d\n"% (total,succ,fail,except)
T+=1
Time.sleep (1)
print ' ===========task end=========== '
Print "total:%d,succ:%d,fail:%d,except:%d"% (total,succ,fail,except)
print ' response maxtime: ', maxtime
print ' response mintime ', mintime
s = raw_input ("Press any Key")
Print "bay!"
Pass
if __name__ = = "__main__":
Main ()
Article content Source:
Http://www.runoob.com/python/python-multithreading.html
Python uses multithreading for stress testing