#!/bin/bash
# performance_monitor.sh
# 性能监控脚本

PACKAGE_NAME="${1:-com.example.app}"
INTERVAL="${2:-5}"
OUTPUT_FILE="performance_${PACKAGE_NAME}_$(date +%Y%m%d_%H%M%S).csv"

if [ -z "$PACKAGE_NAME" ]; then
    echo "Usage: performance_monitor.sh <package_name> [interval_seconds]"
    exit 1
fi

echo "Monitoring performance for: $PACKAGE_NAME"
echo "Interval: ${INTERVAL} seconds"
echo "Output file: $OUTPUT_FILE"
echo "Press Ctrl+C to stop"
echo ""

# 创建CSV文件头
echo "Timestamp,PSS(KB),Private_Dirty(KB),Heap_Size(KB),Heap_Alloc(KB)" > "$OUTPUT_FILE"

# 监控循环
while true; do
    timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    # 获取内存信息
    meminfo=$(adb shell dumpsys meminfo "$PACKAGE_NAME" 2>/dev/null)
    
    if [ -n "$meminfo" ]; then
        # 提取PSS
        pss=$(echo "$meminfo" | grep "TOTAL" | awk '{print $2}')
        
        # 提取Private Dirty
        private_dirty=$(echo "$meminfo" | grep "TOTAL" | awk '{print $5}')
        
        # 提取Heap信息
        heap_size=$(echo "$meminfo" | grep "App Summary" -A 10 | grep "java heap" | awk '{print $4}')
        heap_alloc=$(echo "$meminfo" | grep "App Summary" -A 10 | grep "java heap" | awk '{print $5}')
        
        # 写入CSV
        echo "$timestamp,$pss,$private_dirty,$heap_size,$heap_alloc" >> "$OUTPUT_FILE"
        
        # 显示当前状态
        printf "\r[%s] PSS: %s KB | Heap: %s KB" "$timestamp" "${pss:-N/A}" "${heap_alloc:-N/A}"
    else
        echo "Warning: Could not get memory info for $PACKAGE_NAME"
    fi
    
    sleep "$INTERVAL"
done
