用python开发一个性能压测框架(超级简单)
该框架是一个基础框架,超级简单,已经跑通,可以进行优化扩展
由于工作需要,最近开发了一款python性能压测框架,主要是对后端接口进行多线程压测
主要使用 Python 的 requests 库来发送请求,并使用 threading 或 asyncio 来模拟并发请求
代码如下:
python
import requests
import threading
import time
class PerformanceTester:
def __init__(self, url, num_threads=1, num_requests=10):
self.url = url
self.num_threads = num_threads
self.num_requests = num_requests
self.results = []
def _send_request(self):
start_time = time.time()
response = requests.get(self.url)
end_time = time.time()
elapsed_time = end_time - start_time
self.results.append(elapsed_time)
def run_test(self):
threads = []
for _ in range(self.num_threads):
for _ in range(self.num_requests):
thread = threading.Thread(target=self._send_request)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
avg_response_time = sum(self.results) / len(self.results)
max_response_time = max(self.results)
min_response_time = min(self.results)
print(f"Avg Response Time: {avg_response_time}")
print(f"Max Response Time: {max_response_time}")
print(f"Min Response Time: {min_response_time}")
if __name__ == "__main__":
tester = PerformanceTester("https://example.com/api", num_threads=5, num_requests=20)
tester.run_test()