Files
cuishou-rag-v2/scripts/test_parallel_performance.py
hughhuangandClaude Sonnet 4.5 eb0897a31b feat: 实现性能优化和可配置指标功能 (v2.1.0)
## 主要功能

### 并行评估优化 ⚡
- 实现指标并行执行,提升评估速度 1.25-1.42x
- 创建 ParallelRAGAsEvaluator 并行评估器
- 使用 asyncio.gather() 实现真正的并行

### 可配置指标功能 🎛️
- 支持通过参数启用/禁用特定评估指标
- 创建 ConfigurableRAGAsEvaluator 可配置评估器
- 灵活控制评估速度和质量(2.6-8x 加速)

### 交互式批处理脚本 🖥️
- 更新 evaluate_all_types_advanced.bat 支持优化选项
- 添加 3 种评估模式:完整/快速/极速
- 自动时间预估功能

## 性能提升

| 场景 | 原版 | 优化后 | 节省 |
|------|------|--------|------|
| 单问题 | 8.3分钟 | 1-3分钟 | 5-7分钟 |
| 15问题 | 125分钟 | 15-48分钟 | 77-110分钟 |
| 8系统×15问题 | 16.7小时 | 2-6.4小时 | 10-14.7小时 |

## 新增文件

**核心代码**:
- src/evaluators/parallel_ragas_evaluator.py - 并行评估器
- src/evaluators/configurable_evaluator.py - 可配置评估器

**测试脚本**:
- scripts/test_single_evaluation.py - 单系统评估测试
- scripts/test_report_save.py - 报告保存测试
- scripts/test_parallel_performance.py - 性能对比测试
- scripts/evaluate_single_system_parallel.py - 并行评估脚本
- scripts/evaluate_with_config.py - 可配置评估脚本
- scripts/evaluate_all_types.bat - 基础批处理脚本
- scripts/evaluate_all_types_advanced.bat - 增强批处理脚本(v2)

**文档**:
- docs/PERFORMANCE_ANALYSIS.md - 性能分析
- docs/METRICS_EXPLANATION.md - 指标说明
- docs/PARALLEL_OPTIMIZATION.md - 并行优化方案
- docs/PARALLEL_QUICK_START.md - 并行优化快速开始
- docs/DISABLE_METRICS_GUIDE.md - 禁用指标指南
- docs/OPTIMIZATION_SUMMARY.md - 优化功能总结
- docs/SINGLE_EVALUATION_TEST.md - 单系统测试报告

## 使用方法

### 批处理脚本(推荐)
```bash
scripts\evaluate_all_types_advanced.bat
```

### 命令行脚本
```bash
# 快速评估(禁用 answer_correctness)
python scripts/evaluate_with_config.py --system zht-excel --disable answer_correctness

# 极速评估(仅3个核心指标)
python scripts/evaluate_with_config.py --system zht-excel \
  --enable context_precision faithfulness answer_relevance

# 并行评估
python scripts/evaluate_single_system_parallel.py --system zht-excel
```

## 技术亮点

- 使用 asyncio.gather() 实现指标并行执行
- 支持通过参数灵活配置评估指标
- 保留完整的日志记录功能
- 向后兼容原有评估脚本

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-08 08:45:43 +08:00

241 lines
7.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
并行评估性能对比测试
对比串行和并行执行的性能差异
"""
import sys
import os
import asyncio
import time
from pathlib import Path
from datetime import datetime
# 设置 Windows 控制台编码为 UTF-8
if sys.platform == 'win32':
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
# 添加项目根目录到 Python 路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def create_test_sample():
"""创建测试样本"""
return {
'question_id': 'q001',
'user_input': '签约流程是什么?',
'response': 'PC端签约流程:在还款申请里面→选择到期还款→选择变更还款计划→提交就可以了。',
'reference': '【签约流程】\nPC端签约流程:\n在还款申请里面→选择到期还款→选择变更还款计划→提交就可以了\n⚠️之后有PC端的符合条件的都可以提单,但是只能做展期,也就是说如果原借据已经是36期的就不能做了',
'retrieved_contexts': [
'PC端签约流程:在还款申请里面→选择到期还款→选择变更还款计划→提交就可以了'
],
'category': 'positive',
'type': '简单检索'
}
async def test_sequential():
"""测试串行执行"""
from src.evaluators.parallel_ragas_evaluator import ParallelRAGAsEvaluator
print("\n" + "=" * 80)
print("📊 测试 1: 串行执行(当前模式)")
print("=" * 80)
# 创建串行评估器
evaluator = ParallelRAGAsEvaluator(enable_parallel=False)
# 创建测试样本
sample = create_test_sample()
# 执行评估
start_time = time.time()
print(f"\n开始时间: {datetime.now().strftime('%H:%M:%S')}")
print()
results = await evaluator.evaluate_single(sample)
end_time = time.time()
duration = end_time - start_time
print()
print(f"结束时间: {datetime.now().strftime('%H:%M:%S')}")
print(f"总耗时: {duration:.2f} 秒")
print()
return duration, results
async def test_parallel():
"""测试并行执行"""
from src.evaluators.parallel_ragas_evaluator import ParallelRAGAsEvaluator
print("\n" + "=" * 80)
print("🚀 测试 2: 并行执行(优化模式)")
print("=" * 80)
# 创建并行评估器
evaluator = ParallelRAGAsEvaluator(enable_parallel=True)
# 创建测试样本
sample = create_test_sample()
# 执行评估
start_time = time.time()
print(f"\n开始时间: {datetime.now().strftime('%H:%M:%S')}")
print()
results = await evaluator.evaluate_single(sample)
end_time = time.time()
duration = end_time - start_time
print()
print(f"结束时间: {datetime.now().strftime('%H:%M:%S')}")
print(f"总耗时: {duration:.2f} 秒")
print()
return duration, results
async def run_comparison():
"""运行性能对比测试"""
print()
print("╔" + "=" * 78 + "╗")
print("║" + " " * 20 + "并行评估性能对比测试" + " " * 34 + "║")
print("╚" + "=" * 78 + "╝")
print()
# 测试串行执行
sequential_duration, sequential_results = await test_sequential()
# 等待一下
await asyncio.sleep(2)
# 测试并行执行
parallel_duration, parallel_results = await test_parallel()
# 对比结果
print("=" * 80)
print("📈 性能对比结果")
print("=" * 80)
print()
print(f"串行执行耗时: {sequential_duration:.2f} 秒")
print(f"并行执行耗时: {parallel_duration:.2f} 秒")
print()
if parallel_duration < sequential_duration:
speedup = sequential_duration / parallel_duration
time_saved = sequential_duration - parallel_duration
percentage_saved = (time_saved / sequential_duration) * 100
print(f"⚡ 加速比: {speedup:.2f}x")
print(f"⏱️ 节省时间: {time_saved:.2f} 秒")
print(f"📊 性能提升: {percentage_saved:.1f}%")
else:
slowdown = parallel_duration / sequential_duration
time_wasted = parallel_duration - sequential_duration
print(f"⚠️ 并行反而慢了 {slowdown:.2f}x")
print(f"⏱️ 增加时间: {time_wasted:.2f} 秒")
print()
print("可能原因:")
print(" - API 并发限制")
print(" - 网络带宽瓶颈")
print(" - 系统资源限制")
print()
# 结果一致性检查
print("=" * 80)
print("🔍 结果一致性检查")
print("=" * 80)
print()
all_match = True
for metric_name in sequential_results:
seq_score = sequential_results.get(metric_name)
par_score = parallel_results.get(metric_name)
if seq_score is not None and par_score is not None:
diff = abs(seq_score - par_score)
if diff < 0.0001: # 浮点数精度
print(f"✅ {metric_name}: {seq_score:.4f} (一致)")
else:
print(f"⚠️ {metric_name}: 串行={seq_score:.4f}, 并行={par_score:.4f} (差异={diff:.4f})")
all_match = False
else:
print(f"❌ {metric_name}: 结果不一致")
print()
if all_match:
print("✅ 所有指标结果一致,并行评估安全可用!")
else:
print("⚠️ 部分指标结果存在差异,请检查")
print()
# 预估时间
print("=" * 80)
print("🔮 大规模评估时间预估")
print("=" * 80)
print()
num_questions = 15
print(f"假设评估 {num_questions} 个问题:")
print()
print(f"串行模式: {sequential_duration * num_questions / 60:.1f} 分钟")
print(f"并行模式: {parallel_duration * num_questions / 60:.1f} 分钟")
print()
num_systems = 8
print(f"假设评估 {num_systems} 个系统 × {num_questions} 问题:")
print()
total_sequential = sequential_duration * num_questions * num_systems / 3600
total_parallel = parallel_duration * num_questions * num_systems / 3600
print(f"串行模式: {total_sequential:.1f} 小时")
print(f"并行模式: {total_parallel:.1f} 小时")
print(f"节省时间: {total_sequential - total_parallel:.1f} 小时")
print()
print("=" * 80)
def main():
"""主函数"""
try:
# 运行对比测试
asyncio.run(run_comparison())
print()
print("✅ 测试完成!")
print()
print("📝 建议:")
print(" - 如果并行模式有明显加速,推荐使用并行评估")
print(" - 如果加速不明显,可能受 API 限制影响")
print(" - 可以结合使用更快的模型(qwen-turbo)进一步优化")
print()
return 0
except Exception as e:
print()
print("=" * 80)
print("❌ 测试失败")
print("=" * 80)
print(f"错误类型: {type(e).__name__}")
print(f"错误信息: {e}")
print()
import traceback
traceback.print_exc()
return 1
if __name__ == '__main__':
exit_code = main()
input("\n按 Enter 键退出...")
sys.exit(exit_code)