Python uses multithreading for stress testing

Source: Internet
Author: User

#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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.