-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyze_performance.py
More file actions
357 lines (286 loc) · 14 KB
/
analyze_performance.py
File metadata and controls
357 lines (286 loc) · 14 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
性能数据分析器 - 分析SmartBoostTool录制的性能数据
"""
import os
import json
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime
import glob
from colorama import init, Fore, Style
# 设置matplotlib中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
init(autoreset=True)
class PerformanceAnalyzer:
def __init__(self):
self.results_dir = "results"
def load_baseline_data(self, filepath):
"""加载基准测试数据"""
try:
with open(filepath, 'r', encoding='utf-8') as f:
data = json.load(f)
return data
except Exception as e:
print(f"{Fore.RED}❌ 加载数据失败: {e}")
return None
def compare_baselines(self, baseline_files):
"""比较多个基准测试结果"""
if len(baseline_files) < 2:
print(f"{Fore.YELLOW}⚠️ 需要至少2个基准测试文件进行比较")
return
print(f"{Fore.CYAN}📊 开始比较基准测试...")
# 加载所有基准数据
baselines = {}
for filepath in baseline_files:
data = self.load_baseline_data(filepath)
if data:
test_name = data['test_info']['name']
baselines[test_name] = data
if len(baselines) < 2:
print(f"{Fore.RED}❌ 无法加载足够的有效基准数据")
return
# 创建比较图表
self.create_comparison_charts(baselines)
# 生成比较报告
self.generate_comparison_report(baselines)
def create_comparison_charts(self, baselines):
"""创建比较图表"""
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
fig.suptitle('SmartBoostTool 性能比较分析', fontsize=16, fontweight='bold')
# 准备数据
test_names = list(baselines.keys())
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FCEA2B']
# 图表1: CPU使用率对比
ax1 = axes[0, 0]
cpu_avgs = [baselines[name]['statistics']['cpu_avg'] for name in test_names]
cpu_maxs = [baselines[name]['statistics']['cpu_max'] for name in test_names]
x = np.arange(len(test_names))
width = 0.35
bars1 = ax1.bar(x - width/2, cpu_avgs, width, label='平均CPU使用率',
color=colors[:len(test_names)], alpha=0.7)
bars2 = ax1.bar(x + width/2, cpu_maxs, width, label='最高CPU使用率',
color=colors[:len(test_names)], alpha=0.9)
ax1.set_ylabel('CPU使用率 (%)')
ax1.set_title('CPU使用率对比')
ax1.set_xticks(x)
ax1.set_xticklabels(test_names, rotation=45)
ax1.legend()
ax1.grid(True, alpha=0.3)
# 添加数值标签
for bar in bars1:
height = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., height + 0.5, f'{height:.1f}%',
ha='center', va='bottom', fontsize=8)
# 图表2: 温度对比
ax2 = axes[0, 1]
temp_avgs = [baselines[name]['statistics']['temp_avg'] for name in test_names]
temp_maxs = [baselines[name]['statistics']['temp_max'] for name in test_names]
bars3 = ax2.bar(x - width/2, temp_avgs, width, label='平均温度',
color=colors[:len(test_names)], alpha=0.7)
bars4 = ax2.bar(x + width/2, temp_maxs, width, label='最高温度',
color=colors[:len(test_names)], alpha=0.9)
ax2.set_ylabel('温度 (°C)')
ax2.set_title('CPU温度对比')
ax2.set_xticks(x)
ax2.set_xticklabels(test_names, rotation=45)
ax2.legend()
ax2.grid(True, alpha=0.3)
# 图表3: CPU使用率时序图
ax3 = axes[1, 0]
for i, name in enumerate(test_names[:3]): # 最多显示3个测试的时序
raw_data = baselines[name]['raw_data']
cpu_data = [d['cpu_percent_total'] for d in raw_data]
timestamps = range(len(cpu_data))
ax3.plot(timestamps, cpu_data, label=name, color=colors[i], linewidth=2)
ax3.set_xlabel('时间 (秒)')
ax3.set_ylabel('CPU使用率 (%)')
ax3.set_title('CPU使用率时序对比')
ax3.legend()
ax3.grid(True, alpha=0.3)
# 图表4: 性能稳定性分析
ax4 = axes[1, 1]
cpu_stds = [baselines[name]['statistics']['cpu_std'] for name in test_names]
bars5 = ax4.bar(test_names, cpu_stds, color=colors[:len(test_names)], alpha=0.8)
ax4.set_ylabel('标准差')
ax4.set_title('CPU使用率稳定性 (标准差越小越稳定)')
ax4.set_xticklabels(test_names, rotation=45)
ax4.grid(True, alpha=0.3)
# 添加数值标签
for bar in bars5:
height = bar.get_height()
ax4.text(bar.get_x() + bar.get_width()/2., height + 0.01, f'{height:.2f}',
ha='center', va='bottom', fontsize=8)
plt.tight_layout()
# 保存图表
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
chart_filename = f"performance_comparison_{timestamp}.png"
plt.savefig(os.path.join(self.results_dir, chart_filename), dpi=300, bbox_inches='tight')
print(f"{Fore.GREEN}📈 比较图表已保存: {chart_filename}")
plt.show()
def generate_comparison_report(self, baselines):
"""生成比较报告"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
report_filename = f"comparison_report_{timestamp}.txt"
report_path = os.path.join(self.results_dir, report_filename)
with open(report_path, 'w', encoding='utf-8') as f:
f.write("=" * 60 + "\n")
f.write("SmartBoostTool 性能比较报告\n")
f.write(f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write("=" * 60 + "\n\n")
# 基本统计
f.write("📊 基准测试统计\n")
f.write("-" * 40 + "\n")
test_names = list(baselines.keys())
for name in test_names:
stats = baselines[name]['statistics']
f.write(f"\n🔹 测试: {name}\n")
f.write(f" 平均CPU使用率: {stats['cpu_avg']:.2f}%\n")
f.write(f" 最高CPU使用率: {stats['cpu_max']:.2f}%\n")
f.write(f" CPU使用率稳定性: {stats['cpu_std']:.2f} (标准差)\n")
f.write(f" 平均温度: {stats['temp_avg']:.2f}°C\n")
f.write(f" 最高温度: {stats['temp_max']:.2f}°C\n")
# 性能排名
f.write("\n🏆 性能排名\n")
f.write("-" * 40 + "\n")
# 按平均CPU使用率排序
cpu_ranking = sorted(test_names,
key=lambda x: baselines[x]['statistics']['cpu_avg'],
reverse=True)
f.write("\n📈 平均CPU使用率排名 (高到低):\n")
for i, name in enumerate(cpu_ranking, 1):
cpu_avg = baselines[name]['statistics']['cpu_avg']
f.write(f" {i}. {name}: {cpu_avg:.2f}%\n")
# 按稳定性排序
stability_ranking = sorted(test_names,
key=lambda x: baselines[x]['statistics']['cpu_std'])
f.write("\n⚡ 性能稳定性排名 (稳定到不稳定):\n")
for i, name in enumerate(stability_ranking, 1):
cpu_std = baselines[name]['statistics']['cpu_std']
f.write(f" {i}. {name}: {cpu_std:.2f} (标准差)\n")
# 推荐建议
f.write("\n💡 优化建议\n")
f.write("-" * 40 + "\n")
best_performance = cpu_ranking[0]
most_stable = stability_ranking[0]
f.write(f"🚀 最高性能配置: {best_performance}\n")
f.write(f"⚖️ 最稳定配置: {most_stable}\n")
if best_performance == most_stable:
f.write(f"✅ 建议采用 '{best_performance}' 配置,兼具高性能和稳定性\n")
else:
f.write(f"💭 如需最高性能,选择 '{best_performance}'\n")
f.write(f"💭 如需最佳稳定性,选择 '{most_stable}'\n")
print(f"{Fore.GREEN}📝 比较报告已生成: {report_filename}")
def list_available_baselines(self):
"""列出可用的基准测试文件"""
if not os.path.exists(self.results_dir):
print(f"{Fore.YELLOW}⚠️ 结果目录不存在: {self.results_dir}")
return []
pattern = os.path.join(self.results_dir, "baseline_*.json")
files = glob.glob(pattern)
if not files:
print(f"{Fore.YELLOW}⚠️ 未找到基准测试文件")
return []
print(f"{Fore.CYAN}📁 找到 {len(files)} 个基准测试文件:")
for i, filepath in enumerate(files, 1):
filename = os.path.basename(filepath)
print(f" {i}. {filename}")
return files
def analyze_single_baseline(self, filepath):
"""分析单个基准测试"""
data = self.load_baseline_data(filepath)
if not data:
return
print(f"\n{Fore.CYAN}📊 基准测试分析: {data['test_info']['name']}")
print("-" * 50)
stats = data['statistics']
test_info = data['test_info']
print(f"📝 测试信息:")
print(f" 名称: {test_info['name']}")
print(f" 时间: {test_info['timestamp']}")
print(f" 持续时间: {test_info['duration']}秒")
print(f" CPU核心数: {test_info['system_info']['physical_cores']} 物理 / {test_info['system_info']['logical_cores']} 逻辑")
print(f"\n📈 性能统计:")
print(f" 平均CPU使用率: {stats['cpu_avg']:.2f}%")
print(f" 最高CPU使用率: {stats['cpu_max']:.2f}%")
print(f" 最低CPU使用率: {stats['cpu_min']:.2f}%")
print(f" CPU使用率标准差: {stats['cpu_std']:.2f}")
print(f" 平均温度: {stats['temp_avg']:.2f}°C")
print(f" 最高温度: {stats['temp_max']:.2f}°C")
# 性能评估
print(f"\n🔍 性能评估:")
if stats['cpu_avg'] > 50:
print(f" 🔥 高负载测试 - CPU使用率较高")
elif stats['cpu_avg'] > 20:
print(f" ⚡ 中等负载测试")
else:
print(f" 🌿 轻度负载测试")
if stats['cpu_std'] < 5:
print(f" ✅ 性能稳定 - 标准差较小")
elif stats['cpu_std'] < 15:
print(f" ⚠️ 性能波动适中")
else:
print(f" ❌ 性能波动较大 - 可能存在调度不稳定")
def main():
analyzer = PerformanceAnalyzer()
print(f"{Fore.CYAN}🔍 SmartBoostTool 性能数据分析器")
print("=" * 50)
# 列出可用的基准测试文件
files = analyzer.list_available_baselines()
if not files:
print(f"{Fore.RED}❌ 没有找到可分析的数据文件")
print(f"{Fore.YELLOW}💡 请先运行基准测试: python smart_boost.py --mode baseline")
return
# 用户选择分析模式
print(f"\n{Fore.YELLOW}请选择分析模式:")
print("1. 分析单个基准测试")
print("2. 比较多个基准测试")
print("3. 分析所有基准测试")
try:
choice = input(f"\n{Fore.GREEN}请输入选择 (1-3): ").strip()
if choice == "1":
# 分析单个文件
if len(files) == 1:
analyzer.analyze_single_baseline(files[0])
else:
print(f"\n{Fore.YELLOW}请选择要分析的文件:")
for i, filepath in enumerate(files, 1):
print(f"{i}. {os.path.basename(filepath)}")
file_choice = int(input(f"\n{Fore.GREEN}请输入文件编号: ")) - 1
if 0 <= file_choice < len(files):
analyzer.analyze_single_baseline(files[file_choice])
else:
print(f"{Fore.RED}❌ 无效选择")
elif choice == "2":
# 比较多个文件
if len(files) < 2:
print(f"{Fore.RED}❌ 需要至少2个基准测试文件进行比较")
else:
print(f"\n{Fore.YELLOW}请选择要比较的文件 (用空格分隔编号,如: 1 2 3):")
for i, filepath in enumerate(files, 1):
print(f"{i}. {os.path.basename(filepath)}")
selections = input(f"\n{Fore.GREEN}请输入文件编号: ").strip().split()
selected_files = []
for sel in selections:
try:
idx = int(sel) - 1
if 0 <= idx < len(files):
selected_files.append(files[idx])
except ValueError:
continue
if len(selected_files) >= 2:
analyzer.compare_baselines(selected_files)
else:
print(f"{Fore.RED}❌ 需要选择至少2个有效文件")
elif choice == "3":
# 分析所有文件
analyzer.compare_baselines(files)
else:
print(f"{Fore.RED}❌ 无效选择")
except (ValueError, KeyboardInterrupt):
print(f"\n{Fore.YELLOW}👋 分析已取消")
if __name__ == "__main__":
main()