Skip to content

性能与调试工具:Profiler / Systrace / Perfetto / ADB 实战 ​

一句话:Android 性能 / 调试的全部工具链——Android Studio Profiler 看 CPU/Memory/Network,Systrace/Perfetto 抓系统级 trace,strace/lsof 在 Linux 层 dig,ADB 是连接所有这些工具的瑞士军刀。这一篇是 Android 工程师从"会写代码"升级到"会修线上 bug" 的最后一块拼图。


一、Android Studio Profiler 总览 ​

Run → Profile app → 选 Activity 启动:

┌──────────────────────────────────────────────┐
│  CPU      │  实时 CPU 使用,线程时间线         │
│  Memory   │  Java/Native heap、GC 事件         │
│  Network  │  HTTP 请求时间线、body 抓包          │
│  Energy   │  功耗估算(GPS / 网络 / 屏幕)       │
└──────────────────────────────────────────────┘

每个面板可以深入采样(Sample / Trace / Heap Dump)。

Profiler 是日常 Android 开发的必备——任何"慢""卡""OOM"问题先 Profile 看现场。


二、CPU Profiler:Sample / Trace 两种模式 ​

Sample:每隔 5-50ms 拍一张线程栈快照——开销小,适合长时间观察。统计上看出"哪些方法占用 CPU 最多"。

Trace(method tracing):每个方法调用都记录——精确但开销大(可能让 App 慢 2-5×),只用于短时间(几秒到几十秒)的精细分析。

Sample 用法:

  1. Profiler 进 CPU
  2. 选 "Sampled (Java/Kotlin)"
  3. Record
  4. 操作 App 重现性能问题
  5. Stop
  6. 查看 Flame Chart / Top Down / Bottom Up

Flame Chart:横轴时间,纵轴栈深——一眼看出"哪些函数热"。


三、Memory Profiler:Heap Dump ​

Profiler → Memory
   ↓
点 "Dump Java heap"(垃圾桶图标)
   ↓
.hprof 加载完成,显示按 Class 排序的实例统计

关键操作:

  1. Class List:按内存占用 / 实例数排序
  2. Instance List:展开某 Class,看每个实例
  3. References:某实例的入口引用链(找泄漏路径)

典型流程:

  • Activity 应该只有 1 个 → 显示 5 个 → 4 个泄漏
  • 选其中一个,看 References,沿链找谁持有它

21 篇展开了泄漏排查。


四、Network Profiler ​

显示所有 HTTP / HTTPS 请求(基于 OkHttp / HttpURLConnection 钩子):

  • 时间线:每个请求的开始 / 结束
  • Request / Response Headers
  • Body(JSON 自动格式化)
  • Status / 大小 / 耗时

用例:确认"这个网络请求确实发出去 / 收到响应 / 多大体积 / 多慢"——比写 OkHttp HttpLoggingInterceptor 更直观。

限制:只能看到 App 内 OkHttp / 标准 HTTP 客户端的请求;某些三方 SDK 自己用 native socket 看不到。


五、Energy Profiler ​

估算 App 的功耗——CPU + Network + GPS + 屏幕。

用例:发现"我 App 后台时一直在跑、消耗电"——找出哪个 SDK / 服务在烧电。

精度有限——电量是估算,不是真测。生产分析用真机电量统计:

bash
adb shell dumpsys batterystats --reset       # 重置
# 让 App 跑一段时间
adb shell dumpsys batterystats com.notedx

六、Systrace(已 deprecated,但仍能用) ​

Systrace 是 Android 4.1+ 的系统级追踪工具——记录内核调度、Binder 调用、Choreographer 帧、ART 事件等全系统活动。

bash
# 抓 5 秒 trace,关注 view / app 类别
python systrace.py -t 5 view sched app -o trace.html
# 在 Chrome 打开 trace.html

输出是 HTML,可视化时间线——每个进程、每个线程的活动一目了然。

Systrace 在 Android Studio 4.0+ 被 CPU Profiler 的 "System Trace" 模式集成——直接在 Profiler 里看,不用单独运行 systrace.py。


七、Perfetto:Systrace 的现代化继承者 ​

bash
adb shell perfetto -o /sdcard/trace.pftrace -t 10s \
    -b 32mb \
    --txt \
    -c - <<EOF
buffers: { size_kb: 65536 }
data_sources: {
  config {
    name: "linux.ftrace"
    ftrace_config {
      ftrace_events: "sched/sched_switch"
      ftrace_events: "power/cpu_frequency"
      atrace_categories: "view"
      atrace_categories: "wm"
      atrace_categories: "am"
    }
  }
}
EOF

adb pull /sdcard/trace.pftrace
# 打开 https://ui.perfetto.dev,加载 .pftrace

Perfetto 是 Google 跨平台 trace 工具——比 systrace 更强大、更现代、与 Chrome trace viewer 集成。

ui.perfetto.dev 是浏览器内的可视化界面——加载 trace 文件,看每个 CPU 核 / 进程 / 线程 / VSync 帧。

典型用途:

  • App 启动慢 → trace 看每个阶段在哪个 CPU 上、什么时候
  • 帧丢 → 看 VSync + Choreographer 时间线,找出哪一帧超时
  • Binder 慢 → 看 Binder 调用堆栈
  • ART GC 频繁 → 看 GC 时间线

八、adb logcat:看日志 ​

bash
# 看所有日志
adb logcat

# 只看自己 App
adb logcat --pid=$(adb shell pidof com.notedx)

# 过滤 tag
adb logcat -s MyTag:V                # MyTag 的 V(verbose)以上
adb logcat -s MyTag:D OtherTag:E     # 多个 tag

# 清空缓冲
adb logcat -c

# 显示时间戳
adb logcat -v threadtime

# 写到文件
adb logcat -d > log.txt              # 把当前 buffer 全 dump,不持续

日志级别:V(erbose)< D(ebug)< I(nfo)< W(arn)< E(rror)< F(atal)。

生产 release 默认 strip 掉 V/D 日志——R8 把 Log.v / Log.d 移除(若配置 keep 规则正确)。

Timber 库提供 tag 自动 + 多目标输出(到 Crashlytics 等)——推荐替代裸 Log。


九、adb shell dumpsys:系统服务状态 ​

bash
adb shell dumpsys                        # 列出所有服务名
adb shell dumpsys activity activities    # Activity 栈
adb shell dumpsys activity services      # 所有 Service
adb shell dumpsys activity processes     # 所有 App 进程
adb shell dumpsys activity broadcasts    # 广播队列
adb shell dumpsys package com.notedx     # 包详情
adb shell dumpsys window                 # Window 信息
adb shell dumpsys meminfo com.notedx     # 内存
adb shell dumpsys notification           # 通知
adb shell dumpsys power                  # 电源 / wake lock
adb shell dumpsys batterystats com.notedx # 电量统计
adb shell dumpsys netstats               # 网络
adb shell dumpsys jobscheduler           # JobScheduler
adb shell dumpsys cpuinfo                # CPU 使用
adb shell dumpsys gfxinfo com.notedx     # GPU / 帧率

dumpsys 是 Android 工程师的瑞士军刀——任何系统级状态都能这么查。


十、dumpsys gfxinfo:帧率与丢帧分析 ​

bash
adb shell dumpsys gfxinfo com.notedx framestats

输出:

Profile data in ms:
  Draw  Prepare  Process  Execute
   1.45    0.32     2.17    0.78
   1.52    0.28     2.31    0.69
   ...
Number Missed Vsync: 3
Number High input latency: 0
Number Slow UI thread: 5
Number Slow bitmap uploads: 0
Number Slow issue draw commands: 2

关键指标:

  • Missed Vsync——丢帧次数
  • Slow UI thread——主线程慢于 16ms 的帧数
  • Slow bitmap uploads——Bitmap 上传 GPU 慢(大 Bitmap)
  • Slow draw commands——绘制命令复杂

十一、adb shell am:Activity Manager 命令 ​

bash
# 启动 Activity
adb shell am start -n com.notedx/.MainActivity

# 启动 + 调试
adb shell am start -D -n com.notedx/.MainActivity

# 停 App
adb shell am force-stop com.notedx
adb shell am kill com.notedx

# 模拟 Intent
adb shell am start -a android.intent.action.VIEW -d "https://example.com"

# 发广播
adb shell am broadcast -a com.notedx.SYNC_NOW

# 内存压力模拟
adb shell am send-trim-memory com.notedx COMPLETE

# 慢启动模拟
adb shell am set-debug-app --persistent com.notedx
adb shell am clear-debug-app

am 命令覆盖大部分"启动 / 停止 / 派发事件"操作——CI 测试 / 自动化的关键工具。


十二、adb shell pm:Package Manager 命令 ​

bash
# 列出所有包
adb shell pm list packages | grep notedx

# 看包详情
adb shell pm dump com.notedx

# 启用 / 禁用包
adb shell pm enable com.notedx
adb shell pm disable com.notedx

# 清数据(类似设置里"清除数据")
adb shell pm clear com.notedx

# 卸载
adb shell pm uninstall com.notedx
adb shell pm uninstall --keep-data com.notedx   # 卸载但保留 data 目录

# 强制 R8 优化(用 baseline profile)
adb shell pm compile -m speed -f com.notedx

# 查看权限
adb shell pm grant com.notedx android.permission.CAMERA      # 强制授予(测试用)
adb shell pm revoke com.notedx android.permission.CAMERA

十三、adb shell input:模拟用户输入 ​

bash
# 模拟点击(屏幕坐标)
adb shell input tap 500 1000

# 模拟滑动(起点 → 终点 + 时长 ms)
adb shell input swipe 500 1500 500 500 300

# 模拟按键
adb shell input keyevent KEYCODE_HOME       # Home
adb shell input keyevent KEYCODE_BACK       # 返回
adb shell input keyevent KEYCODE_MENU       # 菜单
adb shell input keyevent KEYCODE_VOLUME_UP  # 音量+

# 输入文本
adb shell input text "hello"

自动化测试基础——CI 上自动跑 App 操作流程,验证主要 path。

KeyEvent.KEYCODE_* 完整清单见 Android 文档。


十四、adb pull / push / install ​

bash
# 文件复制
adb push local.txt /sdcard/                  # PC → 设备
adb pull /sdcard/dump.hprof ./               # 设备 → PC

# 安装 APK
adb install app-release.apk
adb install -r app-release.apk               # -r:替换已存在
adb install -t app-debug.apk                 # -t:允许 testOnly
adb install -d app.apk                       # -d:允许降级

# 安装 AAB(需要 bundletool)
bundletool install-apks --apks=app.apks

十五、adb forward:端口转发 ​

bash
# 把设备的 8080 端口映射到本机 8080
adb forward tcp:8080 tcp:8080

# 现在本机 curl http://localhost:8080 = 设备的 8080

用例:Stetho(已被 deprecated) / Chrome DevTools 调试 WebView / 本地 server 联调。


十六、adb shell pidof / ps / top ​

bash
# 找进程 PID
adb shell pidof com.notedx

# 进程列表
adb shell ps -A | grep notedx

# 实时 top
adb shell top -m 20    # 显示前 20 个进程

# 单进程详情
adb shell ps -A -T | grep notedx   # 主进程 + 所有子线程

十七、/proc/<pid>/ 信息 ​

bash
# CPU / 内存
adb shell cat /proc/<pid>/status | head -30

# 线程数
adb shell ls /proc/<pid>/task | wc -l

# 内存映射
adb shell cat /proc/<pid>/maps | head -20

# 打开的文件描述符
adb shell ls -la /proc/<pid>/fd

# OOM 评分(越大越容易被杀)
adb shell cat /proc/<pid>/oom_score
adb shell cat /proc/<pid>/oom_score_adj

Linux 进程信息在 Android 上完整可用——熟悉 Linux 的就直接用。


十八、strace:跟踪 syscall ​

bash
adb shell su -c "strace -p <pid> -f -e trace=open,read,write"

跟踪进程的系统调用——找出"为什么文件读不到"、"为什么 socket 创建失败"等系统层问题。

需要 root——大多数设备没有。生产排障少用,主要在自己开发机 / Pixel 模拟器 root 后用。


十九、tcpdump:抓包 ​

bash
adb shell tcpdump -i any -s 0 -w /sdcard/cap.pcap port 443
# Ctrl-C
adb pull /sdcard/cap.pcap
# Wireshark 打开

需要 root——非 root 设备抓不到。生产服务联调时,用 Charles / mitmproxy + 设置代理 + 信任证书更常见。


二十、adb shell wm:Window Manager ​

bash
# 改屏幕大小(模拟不同设备)
adb shell wm size 1080x1920
adb shell wm size reset

# 改密度
adb shell wm density 320
adb shell wm density reset

# 强制方向
adb shell wm set-fix-to-user-rotation enabled

适配测试用——不用真换设备就能模拟不同尺寸。


二十一、Android Studio Network Inspector / Database Inspector ​

Network Inspector(Profiler 内)——看 HTTP。

Database Inspector:Run → Database Inspector,实时看 App 的 SQLite 数据库,可以执行 SQL 查询、修改数据。

Background Task Inspector:看 WorkManager / AlarmManager / Job 任务状态。

App Inspection:整合的"实时检查"面板。

这些工具只在 debug build 可用(release 因为优化禁了 inspector 接口)。


二十二、生产环境的诊断:Crashlytics + Macrobenchmark ​

Firebase Crashlytics:线上 crash 收集。每次 crash 上报栈 + 设备 + ROM 版本,聚合到 dashboard。任何上线 App 标配。

Macrobenchmark:实验室性能测试(现代版 21 篇)——StartupTimingMetric / FrameTimingMetric 量化启动 / 滚动性能。CI 上跑可以发现"这次 commit 让启动慢了 50ms"。


二十三、典型排障流程 ​

用户反馈"App 启动慢":

  1. Macrobenchmark 跑 startup,确认现象
  2. CPU Profiler / Perfetto 抓启动 trace
  3. 看 Application.onCreate / 首屏 Activity onCreate 时间
  4. 找出热点(可能是某个 SDK 同步 init)
  5. 优化:延迟 init / 异步 / 移到 IdleHandler
  6. 再 Macrobenchmark 验证

用户反馈"App 滚动卡":

  1. dumpsys gfxinfo 看丢帧统计
  2. Profiler System Trace 抓滚动过程
  3. 看 Choreographer 帧时间线
  4. 看每帧的 measure / layout / draw 时长
  5. 找出超时帧的栈
  6. 优化(View 树嵌套过深 / Bitmap 解码 / Compose 重组过多)

用户反馈"App 内存大":

  1. Profiler Memory 看实时占用
  2. 反复操作,看趋势(只增不降 = 泄漏)
  3. Dump heap,按 Class 看
  4. 找异常多的实例,看 References 引用链
  5. 修泄漏

用户反馈"App 崩了":

  1. Crashlytics 看栈
  2. 用 R8 mapping 反混淆(自动)
  3. 复现:在本地装同版本,按崩溃前操作流程
  4. Profiler / logcat 抓现场

二十四、ADB 安装、卸载、root 等命令清单 ​

bash
# 连接
adb devices                          # 列出连接的设备
adb -s <serial> shell                # 连到特定设备
adb connect 192.168.1.100:5555       # WiFi 调试(需 enable wireless debug)

# 重启
adb reboot
adb reboot bootloader
adb reboot recovery

# 看设备信息
adb shell getprop                    # 所有系统属性
adb shell getprop ro.build.version.sdk   # API Level
adb shell getprop ro.product.model   # 设备型号

# 屏幕
adb shell screencap /sdcard/s.png    # 截图
adb pull /sdcard/s.png
adb shell screenrecord /sdcard/r.mp4 # 录屏(Ctrl-C 结束)

# 设置代理(联调)
adb shell settings put global http_proxy 192.168.1.100:8888
adb shell settings delete global http_proxy   # 清

# root(部分设备)
adb root
adb shell su -c "..."

二十五、踩坑 ​

坑 1:Sample 取代 Trace 用做精细分析。Sample 漏看短方法(<5ms),Trace 看得到但跑得慢。两种工具不同用途。

坑 2:Profiler 在 release 包失效。release 包通常 debuggable=false,Profiler 连不上。测试 release 性能用 Macrobenchmark(它能 profile release 包)。

坑 3:adb logcat 直接打到屏幕被截断。Buffer 满会丢日志。用 -b all -v threadtime > log.txt 完整输出。

坑 4:Perfetto trace 太大。一分钟 trace 可能 100MB+,UI 加载慢。短时间 trace(5-10 秒)更实用。

坑 5:dumpsys gfxinfo reset com.notedx。reset 命令清统计——分析特定操作前 reset,操作完读数据,避免历史数据混淆。

坑 6:把 dumpsys 输出当稳定 API。dumpsys 文本格式版本间会变。用作调试,不要写脚本依赖它输出。

坑 7:adb shell 模拟器路径与真机不一。模拟器 /sdcard/ 可能是 emulated,真机可能挂载 fuse,绝对路径未必一致。用相对路径或 Environment API。

坑 8:screenrecord 时间限制。最长 180 秒,且某些手机限制更严。需要长时间录,分段 + 拼接。

坑 9:adb forward 端口冲突。多个 adb 用同端口会冲突。adb forward --remove tcp:8080 清。

坑 10:R8 mapping 没上传 Play Console。线上 crash 栈是混淆名,看不懂。每个 release 必须配 R8 mapping 上传(Play Publisher 自动)。


全系列完结 ​

22 章读完,你拿到:
├── Android 操作系统的完整心智(Linux + AOSP + ART + Binder + System Services)
├── 四大组件每一个的物理实现(Activity / Service / Receiver / Provider)
├── 主线程模型(Handler / Looper / Choreographer)与 Java 时代异步演化
├── View 系统(三阶段绘制 / XML / ViewBinding / 自定义 View)
├── 资源系统(限定符 / 多语言 / 多密度 / 主题)
├── 旧式存储(SharedPreferences / SQLite / Cursor)与 MediaStore
├── Android 安全模型(权限 / 签名 / Sandbox / SELinux / Keystore)
├── 内存管理(引用模型 / GC / 泄漏诊断)
└── 性能与调试工具链(Profiler / Perfetto / dumpsys / adb)

结合现代版,你拿到的能力是:

  • 写应用:Kotlin + Compose + Hilt + Room + Retrofit(现代版)
  • 读源码:AOSP / 老开源 / SDK 内部(本系列)
  • 修线上 bug:Crashlytics / Profiler / Perfetto / dumpsys(本系列 22 章 + 现代版 21 章)
  • 优化性能:Baseline Profile / Macrobenchmark / 重组分析(两套结合)
  • 诊断疑难:内存泄漏 / Binder 阻塞 / 主线程卡顿(本系列)

一棵树是 Compose 应用,树根是 Android OS。读完两套系列,你既会种树,也懂土。

完结。