当前位置:   article > 正文

python压力测试脚本_压力测试的脚本怎么写

压力测试的脚本怎么写
  1. 一正常情况测试
  2. import json
  3. import requests
  4. import logging
  5. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  6. logger = logging.getLogger(__name__)
  7. restime = []
  8. OK=[]
  9. class Restime():
  10. def API(self,URL2,param):
  11. try:
  12. r = requests.get(URL2, params=param, timeout=10)
  13. r.raise_for_status() # 如果响应状态码不是 200,就主动抛出异常
  14. except requests.RequestException as e:
  15. print(e)
  16. else:
  17. js = json.dumps(r.json())
  18. return [r.json(), r.elapsed.total_seconds(),js]
  19. def circulation(self,num,URL2,param):
  20. for i in range(num):
  21. restime.append(Restime.API(URL2,param)[1])
  22. if json.loads(Restime.API(URL2, param)[2])["message"]=='ok':
  23. OK.append(json.loads(Restime.API(URL2, param)[2])["message"])
  24. logger.info('请求第' + str(i+1) + '次,请求'+json.loads(Restime.API(URL2, param)[2])["message"]+',状态码:'+json.loads(Restime.API(URL2, param)[2])["status"])
  25. else:
  26. logger.info('请求第' + str(i+1) + '次,请求' + json.loads(Restime.API(URL2, param)[2])["message"] + ',状态码:' +
  27. json.loads(Restime.API(URL2, param)[2])["status"])
  28. print('测试次数:',num)
  29. print('响应次数:', len(restime))
  30. print('正常响应次数:', len(OK))
  31. print('总响应最大时长:', max(restime))
  32. print('总响应最小时长:', min(restime))
  33. print('总响应时长:', sum(restime))
  34. print('平均响应时长:', sum(restime) / len(restime))
  35. if __name__ == '__main__':
  36. Restime=Restime()
  37. num=500 #压力测试次数
  38. URL2 = 'http://www.kuaidi100.com/query' #地址
  39. param = {'type' : 'zhongtong' , 'postid' :'73116039505988' } #参数
  40. Restime.circulation(num,URL2,param)
  41. 二多线程测试
  42. import datetime
  43. import json
  44. import requests
  45. import logging
  46. import threading
  47. import time
  48. import sys
  49. from time import sleep,ctime
  50. logging.basicConfig(
  51. level=logging.INFO,
  52. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  53. logger = logging.getLogger(__name__)
  54. reponse_time = []
  55. OK = []
  56. class runScript():
  57. def API(self, url, params):
  58. try:
  59. r = requests.get(url, params=params, timeout=10)
  60. r.raise_for_status() # 如果响应状态码不是 200,就主动抛出异常
  61. except requests.RequestException as e:
  62. print(e)
  63. else:
  64. js = json.dumps(r.json())
  65. # print(r.json()) #json格式的响应数据
  66. # print(r.elapsed.total_seconds()) 响应时间
  67. # print(js) 没有解码的响应数据
  68. return [r.json(), r.elapsed.total_seconds(), js]
  69. def circulation(self,url, params):
  70. # print(Restime.API(url, params)[0]['message'])
  71. reponse_time.append(self.API(url, params)[1])
  72. datas = json.loads(self.API(url, params)[2])["message"]
  73. status = json.loads(self.API(url, params)[2])["status"]
  74. if datas == 'ok':
  75. OK.append(datas)
  76. logger.info('请求状态为:' + datas + ',状态码为:' + status)
  77. else:
  78. logger.info('请求状态为:' + datas + ',状态码为:' + status)
  79. def test(url,params):
  80. Restime = runScript()
  81. Restime.circulation(url, params)
  82. def main(num,url,params):
  83. # print("Starting at:",ctime())
  84. start_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  85. threads = []
  86. for i in range(num):
  87. t = threading.Thread(target=test,args=(url,params))
  88. threads.append(t)
  89. for t in range(num):
  90. threads[t].start()
  91. for j in range(num):
  92. threads[j].join()
  93. # print("All done at:",ctime())
  94. print("Starting at:",start_time)
  95. print("All done at:",datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
  96. # print(OK)
  97. print('响应次数:', len(reponse_time))
  98. print('正常响应次数:', len(OK))
  99. print('总响应最大时长:', max(reponse_time))
  100. print('总响应最小时长:', min(reponse_time))
  101. print('总响应时长:', sum(reponse_time))
  102. print('平均响应时长:', sum(reponse_time) / len(reponse_time))
  103. # print('QPS(TPS)= 并发数/平均响应时间:',num / (sum(reponse_time) / len(reponse_time)))
  104. if __name__ == '__main__':
  105. num = input('输入需要开启的线程数量:')
  106. url = 'http://www.kuaidi100.com/query' #地址
  107. params = {'type': 'zhongtong', 'postid': '73116039505988'} #参数
  108. main(int(num),url,params)

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/1004792
推荐阅读
相关标签
  

闽ICP备14008679号