[root@centosgpt python]# cat stress.py
import argparse
import requests
import threading
from queue import Queue
from queue import Empty
def getarg():
parser = argparse.ArgumentParser(description='benchmarking tool', usage = '%(prog)s [options]')
parser.add_argument( '-n', '--requests', type=int, help='Number of requests to perform' )
parser.add_argument( '-c', '--concurrency', type=int, help='Number of multiple requests to make at a time' )
parser.add_argument( 'url', type=str, help='[https|http][://]hostname[:port]/path' )
args = parser.parse_args()
return args
def dowork(url, b, q, i):
b.wait()
print(f'thread {i} request..')
status, response = getstatus(url)
print(f'thread {i} response..', url, status, response)
if status == 'success':
q.put(response)
def getstatus(url):
try:
r = requests.get(url, timeout=10)
return "success", r.elapsed.total_seconds()
except:
return "error", -1
def total():
cnt = 0
sum = 0.0
list = []
thread_stop = False
while not thread_stop:
try:
response = q.get(True, 5)
q.task_done()
except Empty:
thread_stop = True
break
#print ('get response:')
#print (response)
sum += float(response)
cnt += 1
list.append(response)
list.sort(reverse=True)
value95 = list[round(0.05*len(list))]
average = sum / cnt;
print(f' 95% 响应时间 {round(value95, 2)} second(s)')
print(f' 平均响应时间 {round(average, 2)} second(s)')
return average, value95
def totalrun():
t = threading.Thread(target=total, args=())
t.setDaemon(True)
t.start()
return t
def run(concurrency, url, cnt, q):
b = threading.Barrier(concurrency, timeout=15)
threads = []
for i in range(concurrency):
t = threading.Thread(target=dowork, args=(url,b,q, (cnt)*concurrency+i+1 ))
t.setDaemon(True)
t.start()
threads.append(t)
for t in threads:
t.join()
def stress(concurrency, url, cnt, q):
for i in range(cnt):
run(concurrency, url, i, q)
if __name__ == "__main__":
args = getarg()
q = Queue(args.requests)
print(f'请求总数 {args.requests}')
print(f'并发数 {args.concurrency}')
print(f'URL {args.url}')
stress(args.concurrency, args.url, (int)(args.requests/args.concurrency), q)
t = totalrun()
q.join()
t.join()
评论