- Introduced performance enhancements for ADB exec-out, reducing execution time by 10-20% through the use of Popen with streaming reads, increased buffer sizes, and removal of unnecessary fsync calls. - Implemented optimizations in OCR processing, cutting recognition time by 50% by refining button recognition logic and improving image loading and preprocessing methods. - Added detailed performance diagnostics and configuration options to facilitate further optimizations. - Created new documentation files outlining the performance improvements and recommendations for future enhancements.
225 lines
7.4 KiB
Python
225 lines
7.4 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
ADB 截图基准测试脚本
|
|
|
|
用于测试 ADB exec-out screencap 的实际耗时,帮助诊断截图慢的问题。
|
|
|
|
使用方法:
|
|
1. 确保设备已连接: adb devices
|
|
2. 运行: python test_adb_screenshot_timing.py [device_id]
|
|
如果不提供 device_id,将使用第一个设备
|
|
"""
|
|
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import os
|
|
from typing import Optional
|
|
|
|
|
|
def get_adb_path() -> str:
|
|
"""获取 ADB 路径"""
|
|
# 尝试从环境变量获取
|
|
adb = os.environ.get("ADB_PATH", "adb")
|
|
# 尝试常见路径
|
|
if not os.path.exists(adb):
|
|
common_paths = [
|
|
"adb",
|
|
r"C:\Users\{}\AppData\Local\Android\Sdk\platform-tools\adb.exe".format(os.environ.get("USERNAME", "")),
|
|
r"C:\Android\platform-tools\adb.exe",
|
|
]
|
|
for path in common_paths:
|
|
try:
|
|
result = subprocess.run([path, "version"], capture_output=True, timeout=5)
|
|
if result.returncode == 0:
|
|
return path
|
|
except Exception:
|
|
continue
|
|
return adb
|
|
|
|
|
|
def get_device_id() -> Optional[str]:
|
|
"""获取第一个连接的设备ID"""
|
|
adb = get_adb_path()
|
|
try:
|
|
result = subprocess.run([adb, "devices"], capture_output=True, text=True, timeout=10)
|
|
if result.returncode != 0:
|
|
print(f"[错误] adb devices 失败: {result.stderr}")
|
|
return None
|
|
|
|
lines = result.stdout.strip().split("\n")[1:] # 跳过第一行 "List of devices attached"
|
|
devices = []
|
|
for line in lines:
|
|
if line.strip() and "\t" in line:
|
|
device_id = line.split("\t")[0].strip()
|
|
if device_id:
|
|
devices.append(device_id)
|
|
|
|
if not devices:
|
|
print("[错误] 未找到连接的设备")
|
|
return None
|
|
|
|
if len(devices) > 1:
|
|
print(f"[提示] 找到多个设备: {devices},使用第一个: {devices[0]}")
|
|
|
|
return devices[0]
|
|
except Exception as e:
|
|
print(f"[错误] 获取设备列表失败: {e}")
|
|
return None
|
|
|
|
|
|
def test_exec_out_screencap(device_id: str, iterations: int = 5) -> None:
|
|
"""测试 exec-out screencap 耗时"""
|
|
adb = get_adb_path()
|
|
print(f"\n{'='*60}")
|
|
print(f"测试 ADB exec-out screencap")
|
|
print(f"设备: {device_id}")
|
|
print(f"迭代次数: {iterations}")
|
|
print(f"{'='*60}\n")
|
|
|
|
times = []
|
|
sizes = []
|
|
|
|
for i in range(iterations):
|
|
try:
|
|
start = time.time()
|
|
result = subprocess.run(
|
|
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
|
capture_output=True,
|
|
timeout=15,
|
|
)
|
|
elapsed = (time.time() - start) * 1000.0 # 转换为毫秒
|
|
|
|
if result.returncode == 0:
|
|
size = len(result.stdout)
|
|
times.append(elapsed)
|
|
sizes.append(size)
|
|
print(f" 迭代 {i+1}: {elapsed:.1f}ms, 大小: {size/1024:.1f}KB")
|
|
else:
|
|
print(f" 迭代 {i+1}: 失败 (返回码: {result.returncode})")
|
|
except subprocess.TimeoutExpired:
|
|
print(f" 迭代 {i+1}: 超时 (>15秒)")
|
|
except Exception as e:
|
|
print(f" 迭代 {i+1}: 异常: {e}")
|
|
|
|
if times:
|
|
avg_time = sum(times) / len(times)
|
|
min_time = min(times)
|
|
max_time = max(times)
|
|
avg_size = sum(sizes) / len(sizes) if sizes else 0
|
|
|
|
print(f"\n{'='*60}")
|
|
print(f"统计结果:")
|
|
print(f" 平均耗时: {avg_time:.1f}ms")
|
|
print(f" 最小耗时: {min_time:.1f}ms")
|
|
print(f" 最大耗时: {max_time:.1f}ms")
|
|
print(f" 平均大小: {avg_size/1024:.1f}KB")
|
|
print(f"{'='*60}\n")
|
|
|
|
if avg_time > 3000:
|
|
print("[警告] 平均耗时超过3秒,可能存在问题:")
|
|
print(" - 检查 USB 连接是否稳定")
|
|
print(" - 检查是否使用 Wi-Fi ADB(通常较慢)")
|
|
print(" - 检查设备性能是否正常")
|
|
elif avg_time > 2000:
|
|
print("[提示] 平均耗时超过2秒,建议:")
|
|
print(" - 考虑使用 USB 连接而非 Wi-Fi")
|
|
print(" - 检查设备性能")
|
|
|
|
|
|
def test_shell_screencap_pull(device_id: str, iterations: int = 3) -> None:
|
|
"""测试 shell screencap + pull 耗时(回退方案)"""
|
|
adb = get_adb_path()
|
|
print(f"\n{'='*60}")
|
|
print(f"测试 ADB shell screencap + pull (回退方案)")
|
|
print(f"设备: {device_id}")
|
|
print(f"迭代次数: {iterations}")
|
|
print(f"{'='*60}\n")
|
|
|
|
times = []
|
|
|
|
for i in range(iterations):
|
|
try:
|
|
# 清理旧文件
|
|
subprocess.run([adb, "-s", device_id, "shell", "rm", "/sdcard/DCIM/screenshot.png"],
|
|
capture_output=True, timeout=5)
|
|
|
|
start = time.time()
|
|
|
|
# Step 1: shell screencap
|
|
step1_start = time.time()
|
|
result1 = subprocess.run(
|
|
[adb, "-s", device_id, "shell", "screencap", "-p", "/sdcard/DCIM/screenshot.png"],
|
|
capture_output=True,
|
|
timeout=10,
|
|
)
|
|
step1_dur = (time.time() - step1_start) * 1000.0
|
|
|
|
if result1.returncode != 0:
|
|
print(f" 迭代 {i+1}: shell screencap 失败")
|
|
continue
|
|
|
|
# Step 2: pull
|
|
step2_start = time.time()
|
|
result2 = subprocess.run(
|
|
[adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", "test_screenshot.png"],
|
|
capture_output=True,
|
|
timeout=10,
|
|
)
|
|
step2_dur = (time.time() - step2_start) * 1000.0
|
|
|
|
elapsed = (time.time() - start) * 1000.0
|
|
|
|
if result2.returncode == 0 and os.path.exists("test_screenshot.png"):
|
|
size = os.path.getsize("test_screenshot.png")
|
|
times.append(elapsed)
|
|
print(f" 迭代 {i+1}: 总耗时 {elapsed:.1f}ms (screencap: {step1_dur:.1f}ms, pull: {step2_dur:.1f}ms), 大小: {size/1024:.1f}KB")
|
|
try:
|
|
os.remove("test_screenshot.png")
|
|
except Exception:
|
|
pass
|
|
else:
|
|
print(f" 迭代 {i+1}: pull 失败")
|
|
except Exception as e:
|
|
print(f" 迭代 {i+1}: 异常: {e}")
|
|
|
|
if times:
|
|
avg_time = sum(times) / len(times)
|
|
min_time = min(times)
|
|
max_time = max(times)
|
|
|
|
print(f"\n{'='*60}")
|
|
print(f"统计结果 (回退方案):")
|
|
print(f" 平均耗时: {avg_time:.1f}ms")
|
|
print(f" 最小耗时: {min_time:.1f}ms")
|
|
print(f" 最大耗时: {max_time:.1f}ms")
|
|
print(f"{'='*60}\n")
|
|
|
|
|
|
def main():
|
|
device_id = None
|
|
if len(sys.argv) > 1:
|
|
device_id = sys.argv[1]
|
|
else:
|
|
device_id = get_device_id()
|
|
|
|
if not device_id:
|
|
print("[错误] 无法获取设备ID")
|
|
sys.exit(1)
|
|
|
|
print(f"使用设备: {device_id}")
|
|
print(f"ADB 路径: {get_adb_path()}")
|
|
|
|
# 测试 exec-out(主要方案)
|
|
test_exec_out_screencap(device_id, iterations=5)
|
|
|
|
# 测试 shell + pull(回退方案,较少迭代)
|
|
test_shell_screencap_pull(device_id, iterations=3)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
|
|
|