帮我写一份 python 的压力测试用例
时间: 2024-12-11 07:36:52 浏览: 11
在Python中,压力测试通常用来评估系统在高负载下的性能。以下是一个简单的例子,假设我们正在测试一个HTTP客户端,该客户端从服务器接收数据。我们将创建一个模拟并发请求的场景来进行压力测试:
```python
import requests
from threading import Thread
import time
import random
# 设定目标URL和最大并发数
url = "http://your-server.com/api"
max_threads = 10
requests_per_thread = 100
def load_test():
for _ in range(requests_per_thread):
try:
response = requests.get(url, timeout=1) # 设置超时防止阻塞
if not response.ok:
print(f"Request failed with status code {response.status_code}")
except Exception as e:
print(f"Error during request: {str(e)}")
def stress_test(max_threads):
threads = []
for _ in range(max_threads):
thread = Thread(target=load_test)
threads.append(thread)
thread.start()
# 等待所有线程执行完毕
for thread in threads:
thread.join()
# 运行压力测试
stress_test(max_threads)
```
在这个例子中,`load_test`函数模拟了并发的GET请求,而`stress_test`则启动指定数量的线程同时运行。你可以调整`max_threads`和`requests_per_thread`参数以改变压力程度。
阅读全文