5.25 python 功能(对石家庄铁道大学网站稳定性的检测)

我今天完善了一下我的python大作业中对石家庄铁道大学网站运行时间,同时承载多少用户同时点击之后还能稳定运行,以及对用户访问时响应速度的一个监测。

代码如下:

import requests
import time
import tkinter as tk


class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.master.title("服务器性能测试")
self.create_widgets()

def create_widgets(self):
self.url_label = tk.Label(self.master, text="URL:")
self.url_label.grid(row=0, column=0)

self.url_entry = tk.Entry(self.master)
self.url_entry.grid(row=0, column=1)

self.requests_label = tk.Label(self.master, text="请求数量:")
self.requests_label.grid(row=1, column=0)

self.requests_entry = tk.Entry(self.master)
self.requests_entry.grid(row=1, column=1)

self.timeout_label = tk.Label(self.master, text="超时时间:")
self.timeout_label.grid(row=2, column=0)

self.timeout_entry = tk.Entry(self.master)
self.timeout_entry.grid(row=2, column=1)

self.start_button = tk.Button(self.master, text="开始测试", command=self.start_test)
self.start_button.grid(row=3, column=1)

self.result_label = tk.Label(self.master, text="")
self.result_label.grid(row=4, column=0, columnspan=2, pady=10)

def start_test(self):
url = self.url_entry.get()
num_requests = int(self.requests_entry.get())
timeout = int(self.timeout_entry.get())
self.result_label.config(text=f"正在测试,请稍候...")
self.result_label.update()

# 进行服务器性能测试
total_response_time = 0
total_requests = 0
timeouts = 0
max_response_time = 0

for i in range(num_requests):
# 模拟请求,并记录响应时间和状态码
start_time_i = time.time()
try:
res = requests.get(url, timeout=timeout)
status_code = res.status_code
elapsed_time = time.time() - start_time_i
total_response_time += elapsed_time
total_requests += 1
max_response_time = max(max_response_time, elapsed_time)
except requests.exceptions.Timeout:
timeouts += 1

# 打印测试结果
if total_requests == 0:
self.result_label.config(text=f"所有请求都未响应成功")
else:
success_rate = (total_requests / num_requests) * 100
average_response_time = total_response_time / total_requests
self.result_label.config(text=f"共发送 {num_requests} 个请求,成功率为 {success_rate:.2f}%,\n"
f"平均响应时间为 {average_response_time:.3f} 秒,最大响应时间为 {max_response_time:.3f} 秒。\n"
f"超时次数为 {timeouts}")

self.result_label.update()


if __name__ == "__main__":
root = tk.Tk()
app = Application(master=root)
app.mainloop()
运行截图:

 

posted @ 2023-05-25 21:35  搜一码赛  阅读(13)  评论(0编辑  收藏  举报