TOPIC

磷光与烟火逆流

一个敲代码的程序猿

压力测试

import urllib
import json
import time
import threading
import requests


class Presstest(object):
    """
    并发压力测试
    """

    def __init__(self, press_url):
        self.press_url = press_url

    def test_interface(self, url):
        '''压测接口'''
        global INDEX
        INDEX += 1

        global ERROR_NUM
        global TIME_LENS
        try:
            start = time.time()
            payload = {'img_datas': "img_datas"}
            response_content = self.do_request(url, payload)
            result = json.loads(response_content)
            print(result)
            end = time.time()
            TIME_LENS.append(end - start)
            print('end')
        except Exception as e:
            ERROR_NUM += 1
            print(e)

    def test_onework(self, url):
        '''一次并发处理单个任务'''
        i = 0
        while i < ONE_WORKER_NUM:
            i += 1
            self.test_interface(url)
        time.sleep(LOOP_SLEEP)

    def do_request(self, url, payload):
        '''通用http获取webapi请求结果方法'''

        headers = {
            'Content-Type': 'application/json; charset=UTF-8',
        }
        print(url)
        response = requests.get(url)
        retry_num = 0
        while retry_num < 3:
            if not response or response.status_code == 421:
                time.sleep(1)
                retry_num = retry_num + 1
                continue
            else:
                break
        response_content = response.text
        return response_content

    def run(self):
        '''使用多线程进程并发测试'''
        t1 = time.time()
        Threads = []

        for i in range(THREAD_NUM):
            t = threading.Thread(target=self.test_onework, name="T" + str(self.press_url), args=(self.press_url,))
            t.setDaemon(True)
            Threads.append(t)

        for t in Threads:
            t.start()
        for t in Threads:
            t.join()
        t2 = time.time()

        print("===============压测结果===================")
        print("URL:", self.press_url)
        print("任务数量:", THREAD_NUM, "*", ONE_WORKER_NUM, "=", THREAD_NUM * ONE_WORKER_NUM)
        print("总耗时(秒):", t2 - t1)
        print("每次请求耗时(秒):", (t2 - t1) / (THREAD_NUM * ONE_WORKER_NUM))
        print("每秒承载请求数:", 1 / ((t2 - t1) / (THREAD_NUM * ONE_WORKER_NUM)))
        print("错误数量:", ERROR_NUM)
        print(INDEX)


if __name__ == '__main__':
    press_url = 'https://api.github.com/events'
    TIME_LENS = []
    INDEX = 0
    THREAD_NUM = 10  # 并发线程总数
    ONE_WORKER_NUM = 100  # 每个线程的循环次数
    LOOP_SLEEP = 0  # 每次请求时间间隔(秒)
    ERROR_NUM = 0  # 出错数

    obj = Presstest(press_url)
    obj.run()

原文链接:https: // blog.csdn.net / bugang4663 / article / details / 111906737

posted @ 2021-04-27 18:38  Jacobyang  阅读(77)  评论(0编辑  收藏  举报