Files
douyin_guaji-main/tools/check_screenshot_optimization.py
T
Your Name 478ae69052 chore: Clean up blank lines and enhance code organization
- Removed excessive blank lines from multiple Python scripts and configuration files to improve readability and maintainability.
- Ensured consistent formatting across the project, contributing to a more organized codebase.
- Added new files for testing and analysis, including `test_screenshot_error_handling.py` and `test_screenshot_reuse_optimization.py`, to improve testing coverage and functionality.
2026-01-01 10:04:32 +08:00

300 lines
10 KiB
Python
Raw 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 re
from datetime import datetime
# 设置UTF-8输出
if sys.platform == 'win32':
try:
# 尝试使用reconfigure方法(Python 3.7+)
reconfigure_func = getattr(sys.stdout, 'reconfigure', None)
if reconfigure_func:
reconfigure_func(encoding='utf-8')
except Exception:
try:
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
except Exception:
pass
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def analyze_latest_log():
"""分析最新日志"""
log_dir = "logs"
if not os.path.exists(log_dir):
print("日志目录不存在")
return None
# 查找最新的 unified_*.log 文件
log_files = [f for f in os.listdir(log_dir) if f.startswith('unified_') and f.endswith('.log')]
if not log_files:
print("未找到日志文件")
return None
log_files.sort(key=lambda f: os.path.getmtime(os.path.join(log_dir, f)), reverse=True)
latest_log = os.path.join(log_dir, log_files[0])
print(f"分析日志: {latest_log}")
print()
try:
with open(latest_log, 'r', encoding='utf-8', errors='replace') as f:
lines = f.readlines()
except Exception as e:
print(f"读取日志失败: {e}")
return None
return lines, latest_log
def check_service_startup(lines):
"""检查服务是否启动"""
print("=" * 60)
print("1. 检查服务启动状态")
print("=" * 60)
service_started = False
service_logs = []
for line in lines:
if '截图服务' in line or 'ScreenshotService' in line or '后台截图' in line:
service_started = True
service_logs.append(line.strip())
if service_started:
print("✅ 服务已启动")
print("\n服务启动日志:")
for log in service_logs[:3]: # 显示前3条
print(f" {log[:150]}")
else:
print("❌ 服务未启动")
print(" 日志中未找到服务启动记录")
print(" 可能原因:")
print(" 1. 程序还未重新运行(需要运行新代码)")
print(" 2. 服务启动时发生异常(被静默捕获)")
return service_started
def analyze_screenshot_performance(lines, service_started):
"""分析截图性能"""
print("\n" + "=" * 60)
print("2. 分析截图性能")
print("=" * 60)
# 提取截图耗时
screenshot_times = []
screenshot_logs = []
for line in lines:
# 查找截图耗时
if 'screenshot_elapsed_seconds' in line:
match = re.search(r'screenshot_elapsed_seconds=([\d.]+)', line)
if match:
elapsed = float(match.group(1))
screenshot_times.append(elapsed)
screenshot_logs.append((elapsed, line.strip()[:100]))
# 查找截图成功日志(用于分析时间间隔)
if '[截图]' in line and ('成功' in line or '✓' in line):
timestamp_match = re.search(r'(\d{2}:\d{2}:\d{2})', line)
if timestamp_match:
screenshot_logs.append(('log', line.strip()[:100]))
if screenshot_times:
avg_time = sum(screenshot_times) / len(screenshot_times)
min_time = min(screenshot_times)
max_time = max(screenshot_times)
print(f"截图耗时统计(共 {len(screenshot_times)} 次):")
print(f" 平均耗时: {avg_time:.2f} 秒")
print(f" 最短耗时: {min_time:.2f} 秒")
print(f" 最长耗时: {max_time:.2f} 秒")
print()
# 分析优化效果
if service_started:
print("优化效果分析(服务已启动):")
if avg_time < 0.5:
print(" ✅✅✅ 优化效果非常显著!平均耗时 < 0.5秒")
print(" 说明缓存机制正常工作,响应速度大幅提升")
elif avg_time < 1.0:
print(" ✅✅ 优化效果良好!平均耗时 < 1秒")
print(" 说明服务正常工作,性能有明显提升")
elif avg_time < 2.0:
print(" ✅ 优化效果一般,平均耗时 < 2秒")
print(" 可能原因:缓存未命中,需要等待后台截图")
else:
print(" ⚠️ 优化效果不明显,平均耗时 >= 2秒")
print(" 可能原因:")
print(" 1. 缓存未生效")
print(" 2. 后台截图间隔设置过长")
print(" 3. 服务未正常工作")
else:
print("优化效果分析(服务未启动):")
print(" ⚠️ 这是优化前的性能")
print(f" 平均耗时: {avg_time:.2f} 秒(优化前)")
print(" 预期优化后:")
print(" - 缓存命中: < 0.01秒")
print(" - 缓存未命中: 0.5-1秒")
print(" - 平均耗时: 0.3-0.8秒")
# 显示最近的截图耗时
print("\n最近的截图耗时(最后5次):")
recent_times = [t for t, _ in screenshot_logs if isinstance(t, float)][-5:]
for i, t in enumerate(recent_times, 1):
status = "✅" if t < 1.0 else "⚠️" if t < 2.0 else "❌"
print(f" {status} 第{i}次: {t:.2f}秒")
else:
print("未找到截图耗时数据")
print("可能原因:日志格式不同或未记录耗时")
def check_cache_effectiveness(lines):
"""检查缓存是否生效"""
print("\n" + "=" * 60)
print("3. 检查缓存效果")
print("=" * 60)
# 查找连续的截图操作,分析时间间隔
screenshot_timestamps = []
for line in lines:
if '[截图]' in line and ('成功' in line or '✓' in line):
# 提取时间戳
time_match = re.search(r'(\d{2}:\d{2}:\d{2})', line)
if time_match:
try:
time_str = time_match.group(1)
# 转换为秒数(简化处理)
h, m, s = map(int, time_str.split(':'))
timestamp = h * 3600 + m * 60 + s
screenshot_timestamps.append(timestamp)
except Exception:
pass
if len(screenshot_timestamps) >= 2:
intervals = []
for i in range(1, len(screenshot_timestamps)):
interval = screenshot_timestamps[i] - screenshot_timestamps[i-1]
if interval > 0: # 避免负数
intervals.append(interval)
if intervals:
avg_interval = sum(intervals) / len(intervals)
min_interval = min(intervals)
print(f"截图时间间隔分析(共 {len(intervals)} 个间隔):")
print(f" 平均间隔: {avg_interval:.2f} 秒")
print(f" 最短间隔: {min_interval:.2f} 秒")
print()
if min_interval < 1.0:
print(" ✅ 发现快速连续截图(间隔 < 1秒)")
print(" 说明缓存可能生效,响应速度很快")
elif min_interval < 2.0:
print(" ⚠️ 截图间隔较长(1-2秒)")
print(" 可能是正常操作间隔,或缓存未完全生效")
else:
print(" ⚠️ 截图间隔较长(> 2秒)")
print(" 可能是正常操作间隔")
else:
print("数据不足,无法分析缓存效果")
def check_code_integration():
"""检查代码集成"""
print("\n" + "=" * 60)
print("4. 检查代码集成")
print("=" * 60)
# 检查 douyin_fudai.py
douyin_fudai_path = "douyin/core/douyin_fudai.py"
if os.path.exists(douyin_fudai_path):
with open(douyin_fudai_path, 'r', encoding='utf-8') as f:
content = f.read()
if 'ScreenshotService' in content and 'service.start' in content:
print("✅ douyin_fudai.py 已包含服务启动代码")
else:
print("❌ douyin_fudai.py 未包含服务启动代码")
else:
print(f"❌ 文件不存在: {douyin_fudai_path}")
# 检查 screenshot_operations.py
screenshot_ops_path = "operations/screenshot_operations.py"
if os.path.exists(screenshot_ops_path):
with open(screenshot_ops_path, 'r', encoding='utf-8') as f:
content = f.read()
if 'use_service' in content:
print("✅ screenshot_operations.py 已支持服务模式")
else:
print("❌ screenshot_operations.py 未支持服务模式")
else:
print(f"❌ 文件不存在: {screenshot_ops_path}")
def main():
"""主函数"""
print("\n" + "=" * 60)
print("截图优化效果检查")
print("=" * 60)
print()
# 分析最新日志
result = analyze_latest_log()
if not result:
return 1
lines, log_file = result
# 检查服务启动
service_started = check_service_startup(lines)
# 分析性能
analyze_screenshot_performance(lines, service_started)
# 检查缓存效果
check_cache_effectiveness(lines)
# 检查代码集成
check_code_integration()
# 总结
print("\n" + "=" * 60)
print("检查总结")
print("=" * 60)
if service_started:
print("✅ 服务已启动")
print(" 如果截图耗时仍然较长,可能原因:")
print(" 1. 首次截图需要等待服务启动(1.5秒)")
print(" 2. 缓存未命中,需要等待后台截图完成")
print(" 3. 某些操作强制刷新截图(force=True)")
else:
print("❌ 服务未启动")
print(" 请重新运行程序,服务会在启动时自动启动")
print(" 查看日志中是否有 '[截图服务] 已启动后台截图服务'")
print()
print("优化效果验证方法:")
print("1. 重新运行程序")
print("2. 观察首次截图后的后续截图速度")
print("3. 如果缓存命中,响应时间应该 < 0.1秒")
print("4. 运行: python tools/analyze_screenshot_logs.py")
return 0
if __name__ == '__main__':
sys.exit(main())