-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_performance.py
More file actions
98 lines (75 loc) · 2.43 KB
/
test_performance.py
File metadata and controls
98 lines (75 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
性能测试脚本
"""
import os
import time
import psutil
import subprocess
import logging
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('performance_test.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
def get_process_info(pid):
"""获取进程信息"""
try:
process = psutil.Process(pid)
cpu_percent = process.cpu_percent(interval=1)
memory_mb = process.memory_info().rss / (1024 * 1024)
return cpu_percent, memory_mb
except psutil.NoSuchProcess:
return None, None
def test_performance():
"""测试应用程序性能"""
logger.info("开始性能测试...")
# 启动应用程序
app_process = subprocess.Popen(["python", "main.py"])
pid = app_process.pid
logger.info(f"应用程序启动,PID: {pid}")
# 等待应用程序初始化
time.sleep(3)
# 运行测试5分钟
test_duration = 300 # 5分钟
start_time = time.time()
max_cpu = 0
max_memory = 0
while time.time() - start_time < test_duration:
cpu, memory = get_process_info(pid)
if cpu is None or memory is None:
logger.error("进程已退出,测试结束")
break
# 更新最大值
if cpu > max_cpu:
max_cpu = cpu
if memory > max_memory:
max_memory = memory
logger.info(f"CPU使用率: {cpu:.2f}%, 内存占用: {memory:.2f} MB")
# 检查资源占用是否符合要求
if cpu > 5:
logger.warning(f"CPU使用率超过5%: {cpu:.2f}%")
if memory > 50:
logger.warning(f"内存占用超过50MB: {memory:.2f} MB")
time.sleep(5)
# 停止应用程序
app_process.terminate()
app_process.wait()
logger.info(f"性能测试结束")
logger.info(f"最大CPU使用率: {max_cpu:.2f}%")
logger.info(f"最大内存占用: {max_memory:.2f} MB")
# 检查测试结果
if max_cpu <= 5 and max_memory <= 50:
logger.info("性能测试通过: 资源占用符合要求")
return True
else:
logger.error("性能测试失败: 资源占用超出要求")
return False
if __name__ == "__main__":
test_performance()