app=$1
round=$2
dir=$3

# iqiyi com.qiyi.video/com.qiyi.video.WelcomeActivity

prev_alloc=$(adb shell cat /sys/kernel/mm/transparent_hugepage/hugepages-64kB/stats/anon_fault_alloc)
prev_alloc_fallback=$(adb shell cat /sys/kernel/mm/transparent_hugepage/hugepages-64kB/stats/anon_fault_fallback)

adb shell "simpleperf stat -e dTLB-loads,dTLB-load-misses,iTLB-loads,iTLB-load-misses,page-faults,raw-stall-backend-mem --app $app --duration 3 -o /data/local/tmp/simpleperf-"$app"-"$round".txt" &
adb shell "perfetto -c /data/misc/perfetto-configs/perfconf.txt --txt -o /data/misc/perfetto-traces/trace-"$app"-"$round".ptrace" &

perfetto_pid=$!
echo perfetto_pid is $perfetto_pid

# 启动应用
sleep 1

if [ "$app" == "com.qiyi.video" ]; then
	activity="com.qiyi.video/com.qiyi.video.WelcomeActivity"
elif [ "$app" == "com.netease.cloudmusic" ]; then
	activity="com.netease.cloudmusic/com.netease.cloudmusic.activity.IconChangeDefaultAlias"
else
	activity=$(adb shell dumpsys package $app | grep -A 1 -w "android.intent.action.MAIN:" | head -n 2 | tail -n 1 | awk '{print $2}')
fi

if [ -z "$activity" ]; then
	continue
fi
echo "starting $activity"
adb shell am start -n $activity

# 睡眠15s等待perfetto退出
sleep 12
wait

# 后面的dumpsys meminfo也会分配大页
# 所以先看分配大页数
alloc=$(adb shell cat /sys/kernel/mm/transparent_hugepage/hugepages-64kB/stats/anon_fault_alloc)
alloc_fallback=$(adb shell cat /sys/kernel/mm/transparent_hugepage/hugepages-64kB/stats/anon_fault_fallback)

adb shell "dumpsys meminfo --package $app" > $dir/meminfo-"$app"-"$round".txt

# 计算大页分配成功率
inc_alloc=$((alloc-prev_alloc))
inc_alloc_fallback=$((alloc_fallback-prev_alloc_fallback))
inc_total=$((inc_alloc+inc_alloc_fallback))
if [ $inc_total -ne 0 ]; then
	inc_ratio=$(echo "scale=4; $inc_alloc / $inc_total" | bc)
else
	inc_ratio=1
fi

echo -e "$inc_ratio\t$inc_total" > $dir/ratio-"$app"-"$round".txt

sleep 3

adb pull /data/misc/perfetto-traces/trace-"$app"-"$round".ptrace $dir/traces
adb pull /data/local/tmp/simpleperf-"$app"-"$round".txt $dir/

adb shell "rm /data/misc/perfetto-traces/trace-"$app"-"$round".ptrace"
adb shell "rm /data/local/tmp/simpleperf-"$app"-"$round".txt"

