使用python对URL进行并发压力测试

背景:使用python进行并发请求,进行压力测试

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import threading
import urllib2
import time
from Queue import Queue

# 配置参数
url = "http://192.xxx10"  # 替换为你要测试的URL
num_requests = 10000000         # 总请求数
concurrent_threads = 400     # 并发线程数



# 记录成功和失败的请求数
success_count = 0
failure_count = 0
lock = threading.Lock()

def send_request(q):
    global success_count, failure_count
    while not q.empty():
        try:
            response = urllib2.urlopen(url, timeout=5)
            if response.getcode() == 200:
                with lock:
                    success_count += 1
                    qps = success_count % 100
                    if qps == 0:
                        print success_count
            else:
                with lock:
                    failure_count += 1
        except Exception as e:
            with lock:
                failure_count += 1
        finally:
            q.task_done()

if __name__ == "__main__":
    print "Starting load test on %s" % url
    start_time = time.time()

    # 创建队列并填充任务
    q = Queue(maxsize=num_requests)
    for _ in range(num_requests):
        q.put(1)

    # 创建并启动线程
    threads = []
    for i in range(concurrent_threads):
        t = threading.Thread(target=send_request, args=(q,))
        t.daemon = True
        t.start()
        threads.append(t)

    # 等待所有任务完成
    q.join()

    # 结束时间
    end_time = time.time()
    elapsed_time = end_time - start_time

    print "\n--- Load Test Results ---"
    print "Total Requests: %d" % num_requests
    print "Concurrency Level: %d" % concurrent_threads
    print "Successful Requests: %d" % success_count
    print "Failed Requests: %d" % failure_count
    print "Time taken for tests: %.2f seconds" % elapsed_time
    print "Requests per second: %.2f" % (num_requests / elapsed_time)
posted @ 2025-01-20 16:10  帅帅啊  阅读(35)  评论(0)    收藏  举报