#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 简化版并行OCR性能对比测试 直接使用提供的图片进行测试 """ import os import sys import time from concurrent.futures import ThreadPoolExecutor from PIL import Image import numpy as np def test_ocr_with_config(image_path, config_name, omp_threads, max_workers, num_tasks=6): """使用指定配置测试OCR""" print(f"\n{'='*70}") print(f"{config_name}") print(f"{'='*70}") print(f"OMP_NUM_THREADS={omp_threads}, max_workers={max_workers}, 任务数={num_tasks}") print() # 设置OMP old_omp = os.environ.get('OMP_NUM_THREADS', '4') os.environ['OMP_NUM_THREADS'] = str(omp_threads) # 加载图片 try: img = Image.open(image_path) if img.mode != 'RGB': img = img.convert('RGB') img_np = np.array(img) print(f"图片: {os.path.basename(image_path)}") print(f"尺寸: {img.size[0]}x{img.size[1]} 像素") print() except Exception as e: print(f"[ERROR] 无法加载图片: {e}") os.environ['OMP_NUM_THREADS'] = old_omp return None # 初始化OCR try: from operations.ocr_operations import OCRProcessor ocr_processor = OCRProcessor() ocr_processor._ensure_ocr() if ocr_processor.ocr is None: print("[ERROR] OCR引擎未初始化") os.environ['OMP_NUM_THREADS'] = old_omp return None print(f"OCR引擎: {ocr_processor.ocr_type}") print() except Exception as e: print(f"[ERROR] OCR引擎初始化失败: {e}") os.environ['OMP_NUM_THREADS'] = old_omp return None # OCR任务函数 def ocr_task(task_id): try: start = time.time() if ocr_processor.ocr_type == "easyocr": result = ocr_processor.ocr.readtext(img_np) else: result = ocr_processor.ocr.ocr(img_np) from Underlying_Operations import underlying_operations ops = underlying_operations() text = ops.extract_ocr_content(result) elapsed = (time.time() - start) * 1000 return {'task_id': task_id, 'text': text, 'time': elapsed, 'success': True} except Exception as e: return {'task_id': task_id, 'text': '', 'time': 0, 'success': False, 'error': str(e)} # 执行并行OCR print("开始并行OCR测试...") start_time = time.time() results = [] with ThreadPoolExecutor(max_workers=max_workers) as executor: futures = {executor.submit(ocr_task, i+1): i+1 for i in range(num_tasks)} for future in futures: try: result = future.result() results.append(result) status = "✓" if result['success'] else "✗" print(f" {status} 任务{result['task_id']}: {result['time']:.0f}ms, 结果: {result['text'][:20] if result['text'] else '(空)'}") except Exception as e: print(f" ✗ 任务失败: {e}") total_elapsed = (time.time() - start_time) * 1000 # 恢复OMP设置 os.environ['OMP_NUM_THREADS'] = old_omp # 统计 successful = [r for r in results if r['success']] total_task_time = sum(r['time'] for r in successful) avg_task_time = total_task_time / len(successful) if successful else 0 print() print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)") print(f"任务总耗时: {total_task_time:.0f}ms") print(f"平均每个任务: {avg_task_time:.0f}ms") if total_task_time > 0: efficiency = total_task_time / total_elapsed print(f"并行效率: {efficiency:.2f}x (理想值: {num_tasks:.1f}x)") print() return { 'total_time': total_elapsed, 'avg_task_time': avg_task_time, 'config': config_name } def main(): """主函数""" default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png" if len(sys.argv) > 1: image_path = sys.argv[1] else: image_path = default_image if not os.path.isabs(image_path): project_root = os.path.dirname(os.path.abspath(__file__)) image_path = os.path.join(project_root, image_path) if not os.path.exists(image_path): print(f"[ERROR] 图片文件不存在: {image_path}") return print("=" * 70) print("并行OCR性能对比测试(简化版)") print("=" * 70) print() print(f"测试图片: {os.path.basename(image_path)}") # 获取系统信息 cpu_count = os.cpu_count() or 4 print(f"CPU核心数: {cpu_count}") try: from operations.screenshot_service import get_optimal_workers optimal_workers = get_optimal_workers() print(f"推荐线程池大小: {optimal_workers}") except: optimal_workers = 6 num_tasks = 6 print(f"测试任务数: {num_tasks}") print() # 测试1: 优化前 result_old = test_ocr_with_config( image_path, "优化前配置 (OMP=1, workers=6)", omp_threads=1, max_workers=6, num_tasks=num_tasks ) time.sleep(1) # 等待系统稳定 # 测试2: 优化后 result_new = test_ocr_with_config( image_path, "优化后配置 (OMP=4, workers=10)", omp_threads=4, max_workers=optimal_workers, num_tasks=num_tasks ) # 对比结果 print() print("=" * 70) print("性能对比总结") print("=" * 70) print() if result_old and result_new: old_time = result_old['total_time'] new_time = result_new['total_time'] speedup = old_time / new_time if new_time > 0 else 0 print(f"优化前总耗时: {old_time:.0f}ms ({old_time/1000:.2f}秒)") print(f"优化后总耗时: {new_time:.0f}ms ({new_time/1000:.2f}秒)") print(f"性能提升: {speedup:.2f}x") print(f"时间减少: {(1 - new_time/old_time)*100:.1f}%") print() old_avg = result_old['avg_task_time'] new_avg = result_new['avg_task_time'] print(f"优化前平均任务耗时: {old_avg:.0f}ms") print(f"优化后平均任务耗时: {new_avg:.0f}ms") if new_avg > 0: print(f"单任务性能提升: {old_avg/new_avg:.2f}x") print() print("=" * 70) print("测试完成") print("=" * 70) if __name__ == "__main__": main()