performance_test.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. #!/usr/bin/env python3
  2. """
  3. 性能测试脚本 - 对比原版本和优化版本的性能
  4. """
  5. import time
  6. import os
  7. import sqlite3
  8. import subprocess
  9. import sys
  10. from datetime import datetime
  11. def get_db_stats(db_path):
  12. """获取数据库统计信息"""
  13. if not os.path.exists(db_path):
  14. return None
  15. conn = sqlite3.connect(db_path)
  16. c = conn.cursor()
  17. stats = {}
  18. # 文件进度统计
  19. c.execute("SELECT COUNT(*) FROM file_progress WHERE status = 'completed'")
  20. stats['completed_files'] = c.fetchone()[0]
  21. c.execute("SELECT COUNT(*) FROM file_progress")
  22. stats['total_files'] = c.fetchone()[0]
  23. # 翻译缓存统计(如果存在)
  24. try:
  25. c.execute("SELECT COUNT(*) FROM translation_cache")
  26. stats['cached_translations'] = c.fetchone()[0]
  27. c.execute("SELECT AVG(access_count) FROM translation_cache")
  28. avg_access = c.fetchone()[0]
  29. stats['avg_cache_access'] = avg_access if avg_access else 0
  30. except:
  31. stats['cached_translations'] = 0
  32. stats['avg_cache_access'] = 0
  33. conn.close()
  34. return stats
  35. def backup_database():
  36. """备份现有数据库"""
  37. db_path = "translation_progress.db"
  38. if os.path.exists(db_path):
  39. backup_path = f"translation_progress_backup_{int(time.time())}.db"
  40. os.rename(db_path, backup_path)
  41. print(f"数据库已备份到: {backup_path}")
  42. return backup_path
  43. return None
  44. def restore_database(backup_path):
  45. """恢复数据库"""
  46. if backup_path and os.path.exists(backup_path):
  47. db_path = "translation_progress.db"
  48. if os.path.exists(db_path):
  49. os.remove(db_path)
  50. os.rename(backup_path, db_path)
  51. print(f"数据库已从备份恢复: {backup_path}")
  52. def run_test(script_name, config_file=None, test_files=3):
  53. """运行测试"""
  54. print(f"\n{'='*60}")
  55. print(f"测试脚本: {script_name}")
  56. if config_file:
  57. print(f"配置文件: {config_file}")
  58. print(f"测试文件数量: {test_files}")
  59. print(f"{'='*60}")
  60. # 记录开始时间
  61. start_time = time.time()
  62. # 构建命令
  63. cmd = [sys.executable, script_name]
  64. # 设置环境变量指定配置文件
  65. env = os.environ.copy()
  66. if config_file:
  67. env['TRANSLATION_CONFIG'] = config_file
  68. try:
  69. # 运行脚本(仅处理前几个文件用于测试)
  70. print(f"开始时间: {datetime.now().strftime('%H:%M:%S')}")
  71. # 这里需要修改脚本以支持限制处理文件数量
  72. # 或者手动中断测试
  73. # 由于测试目的,我们设置一个较短的超时时间
  74. result = subprocess.run(
  75. cmd,
  76. env=env,
  77. capture_output=True,
  78. text=True,
  79. timeout=300 # 5分钟超时
  80. )
  81. end_time = time.time()
  82. duration = end_time - start_time
  83. print(f"结束时间: {datetime.now().strftime('%H:%M:%S')}")
  84. print(f"运行时长: {duration:.2f} 秒")
  85. # 获取数据库统计
  86. stats = get_db_stats("translation_progress.db")
  87. return {
  88. 'script': script_name,
  89. 'duration': duration,
  90. 'stats': stats,
  91. 'success': result.returncode == 0,
  92. 'output': result.stdout,
  93. 'error': result.stderr
  94. }
  95. except subprocess.TimeoutExpired:
  96. end_time = time.time()
  97. duration = end_time - start_time
  98. print(f"测试超时 (5分钟)")
  99. print(f"运行时长: {duration:.2f} 秒")
  100. # 获取数据库统计
  101. stats = get_db_stats("translation_progress.db")
  102. return {
  103. 'script': script_name,
  104. 'duration': duration,
  105. 'stats': stats,
  106. 'success': False,
  107. 'timeout': True,
  108. 'output': "测试超时",
  109. 'error': "超时"
  110. }
  111. except Exception as e:
  112. print(f"测试失败: {e}")
  113. return {
  114. 'script': script_name,
  115. 'duration': 0,
  116. 'stats': None,
  117. 'success': False,
  118. 'error': str(e)
  119. }
  120. def compare_results(results):
  121. """对比测试结果"""
  122. print(f"\n{'='*80}")
  123. print("📊 性能对比结果")
  124. print(f"{'='*80}")
  125. for i, result in enumerate(results, 1):
  126. print(f"\n{i}. {result['script']}")
  127. print(f" 运行时长: {result['duration']:.2f} 秒")
  128. print(f" 执行状态: {'✅ 成功' if result['success'] else '❌ 失败'}")
  129. if result.get('timeout'):
  130. print(f" 状态说明: ⏰ 超时")
  131. if result['stats']:
  132. stats = result['stats']
  133. print(f" 完成文件: {stats['completed_files']}/{stats['total_files']}")
  134. print(f" 缓存条目: {stats['cached_translations']}")
  135. print(f" 平均缓存访问: {stats['avg_cache_access']:.1f}")
  136. if result.get('error') and result['error'] != "超时":
  137. print(f" 错误信息: {result['error'][:100]}...")
  138. # 性能对比
  139. if len(results) >= 2:
  140. print(f"\n🚀 性能提升分析:")
  141. original = results[0]
  142. optimized = results[1]
  143. if original['success'] and optimized['success']:
  144. time_improvement = (original['duration'] - optimized['duration']) / original['duration'] * 100
  145. print(f" 时间优化: {time_improvement:+.1f}%")
  146. if optimized['stats'] and optimized['stats']['cached_translations'] > 0:
  147. print(f" 缓存效果: {optimized['stats']['cached_translations']} 条翻译被缓存")
  148. print(f" 缓存复用: 平均每条翻译被访问 {optimized['stats']['avg_cache_access']:.1f} 次")
  149. def main():
  150. """主测试函数"""
  151. print("🧪 EPUB翻译器性能测试")
  152. print("本测试将对比原版本和优化版本的性能差异")
  153. # 检查脚本文件是否存在
  154. original_script = "translate_epub_v4(单线程版本)V3.py"
  155. optimized_script = "translate_epub_v4_optimized.py"
  156. optimized_config = "config_optimized.yaml"
  157. if not os.path.exists(original_script):
  158. print(f"❌ 找不到原始脚本: {original_script}")
  159. return
  160. if not os.path.exists(optimized_script):
  161. print(f"❌ 找不到优化脚本: {optimized_script}")
  162. return
  163. # 备份现有数据库
  164. backup_path = backup_database()
  165. results = []
  166. try:
  167. # 测试1: 原始版本
  168. print(f"\n🔄 测试 1/2: 原始版本")
  169. result1 = run_test(original_script)
  170. results.append(result1)
  171. # 清理数据库准备下一个测试
  172. if os.path.exists("translation_progress.db"):
  173. os.remove("translation_progress.db")
  174. # 测试2: 优化版本
  175. print(f"\n🔄 测试 2/2: 优化版本")
  176. result2 = run_test(optimized_script, optimized_config)
  177. results.append(result2)
  178. # 对比结果
  179. compare_results(results)
  180. except KeyboardInterrupt:
  181. print("\n⏹️ 测试被用户中断")
  182. finally:
  183. # 恢复原始数据库
  184. if backup_path:
  185. restore_database(backup_path)
  186. print(f"\n✅ 测试完成")
  187. if __name__ == "__main__":
  188. main()