Android 性能优化(24)*性能工具之「Traceview,dmtracedump」Profiling with Traceview and dmtracedump :记录并查看函数调用栈*
Profiling with Traceview and dmtracedump
In this document
- Traceview Layout Traceview工具界面介绍
- Timeline Panel 时间线面板
- Profile Panel 数据面板 各行列介绍
- Creating Trace Files 用代码生成trace文件
- Copying Trace Files to a Host Machine 把trace文件从设备上拷贝出来
- Viewing Trace Files in Traceview 在ddms中生成并查看trace文件
- Using dmtracedump 使用 dmtracedump 工具把trace文件中的调用栈按树状显示
- about dmtracedump dmtracedump简介
- dmtracedump sample dmtracedump示例
- Traceview Known Issues Traceview的两个bug
Traceview is a graphical viewer for execution logs that you create by using the Debug class to log tracing information in your code. Traceview can help you debug your application and profile its performance.
1.工具界面介绍
When you have a trace log file (generated by adding tracing code to your application or by DDMS), you can load the log files in Traceview, which displays the log data in two panels:
- A timeline panel -- describes when each thread and method started and stopped
- A profile panel -- provides a summary of what happened inside a method
The sections below provide addition information about the traceview output panes.
1.1时间线面板中各线介绍
Figure 1 shows a close up of the timeline panel. Each thread’s execution is shown in its own row, with time increasing to the right. Each method is shown in another color (colors are reused in a round-robin fashion starting with the methods that have the most inclusive time). The thin lines underneath the first row show the extent (entry to exit) of all the calls to the selected method.
下图中每个线程占一行。每个函数一个颜色,细线代表选中函数的调用区间。

Figure 1. The Traceview Timeline Panel
上图中的黑色区域中其实有多个颜色的函数集中在一起,放大后显示如下图,每个颜色都是一个函数调用。用鼠标滚轮可广大缩小,按住可托动。
可以按包名排序,这样就可以快速查看你的工程包里的和函数的运行情况。如下图中的com.e.weixin.main.view.SplashFragment.onCreate()就比其它函数占用更多的cpu。


1.2数据面板 各行列介绍
Figure 2 shows the profile pane, a summary of all the time spent in a method. The table shows both the inclusive and exclusive times (as well as the percentage of the total time).
Exclusive time is the time spent in the method. Inclusive time is the time spent in the method plus the time spent in any called functions. We refer to calling methods as "parents" and called methods as "children." When a method is selected (by clicking on it), it expands to show the parents and children. Parents are shown with a purple background and children with a yellow background.
Exclusive time 是方法本身执行的时间。 Inclusive time 是 Exclusive time + 调用的其它方法的时间。
The last column in the table shows the number of calls to this method plus the number of recursive calls. The last column shows the number of calls out of the total number of calls made to that method. In this view, we can see that there were 14 calls to LoadListener.nativeFinished(); looking at the timeline panel shows that one of those calls took an unusually long time.
Calls+Rec列是 调用本方法的次数+本方法递归的次数。

Figure 2. The Traceview Profile Panel
2.用代码生成trace文件
2.1简介
To use Traceview, you need to generate log files containing the trace information you want to analyze.
There are two ways to generate trace logs:
使用Traceview前要先生成trace文件
生成trace文件的两种方式:用代码记录 和 用 ddms记录
- Include the
Debugclass in your code and call its methods such asstartMethodTracing()andstopMethodTracing(), to start and stop logging of trace information to disk. This option is very precise because you can specify exactly where to start and stop logging trace data in your code.1.有源码时,在代码中调用
startMethodTracing()和stopMethodTracing()精确记录它们之间的函数调用痕迹。 - Use the method profiling feature of DDMS to generate trace logs. This option is less precise because you do not modify code, but rather specify when to start and stop logging with DDMS. Although you have less control on exactly where logging starts and stops, this option is useful if you don't have access to the application's code, or if you do not need precise log timing.
2.没有源码时,在ddms中生成trace文件。这种方法不精确,但可用。
Before you start generating trace logs, be aware of the following restrictions:
记录函数调用栈的前提:
- If you are using the
Debugclass, your application must have permission to write to external storage (WRITE_EXTERNAL_STORAGE).1,用代码记录时,要有 WRITE_EXTERNAL_STORAGE 权限。
- If you are using DDMS:
- Android 2.1 and earlier devices must have an SD card present and your application must have permission to write to the SD card.
2.1及之前的设备要有sd卡和相关权限。
- Android 2.2 and later devices do not need an SD card. The trace log files are streamed directly to your development machine.
- Android 2.1 and earlier devices must have an SD card present and your application must have permission to write to the SD card.
This document focuses on using the Debug class to generate trace data. For more information on using DDMS to generate trace data, see Using the Dalvik Debug Monitor Server.
2.2用代码生成trace文件
To create the trace files, include the Debug class and call one of the startMethodTracing() methods. In the call, you specify a base name for the trace files that the system generates. To stop tracing, call stopMethodTracing(). These methods start and stop method tracing across the entire virtual machine. For example, you could call startMethodTracing() in your activity's onCreate() method, and call stopMethodTracing() in that activity's onDestroy() method.
在activity中开发记录痕迹的示例:如果在MainActivity的onCreate中 startMethodTracing,在onDestory中 stopMethodTracing 那么生成的trace文件很大,可以只对感兴趣的代码记录。
// start tracing to "/sdcard/calc.trace"
Debug.startMethodTracing("calc");
// ...
// stop tracing
Debug.stopMethodTracing();
When your application calls startMethodTracing(), the system creates a file called <trace-base-name>.trace. This contains the binary method trace data and a mapping table with thread and method names.
当调用startMethodTracing()时,生成一个名为 "<trace-base-name>.trace" 的记录文件。包含方法名,线程等信息。
The system then begins buffering the generated trace data, until your application calls stopMethodTracing(), at which time it writes the buffered data to the output file. If the system reaches the maximum buffer size before you call stopMethodTracing(), the system stops tracing and sends a notification to the console.
stopMethodTracing()停止记录,如果在记录缓冲満后,还没有停止,会有console上有通知。
Interpreted code runs more slowly when profiling is enabled. Don't try to generate absolute timings from the profiler results (such as, "function X takes 2.5 seconds to run"). The times are only useful in relation to other profile output, so you can see if changes have made the code faster or slower relative to a previous profiling run.
通常记录所耗时间没有必要,它会使应用变慢。
In Android 4.4 and later, you can use sample-based profiling to profile with less runtime performance impact. To enable sample profiling, call startMethodTracingSampling() with a specified sampling interval. The system will then gather samples periodically until tracing is stopped via stopMethodTracing().
4.4以后,可以调用 startMethodTracingSampling(),它可以周期的记录。
3.把trace文件从设备上拷贝出来
After your application has run and the system has created your trace files <trace-base-name>.trace on a device or emulator, you must copy those files to your development computer. You can use adb pull to copy the files. Here's an example that shows how to copy an example file, calc.trace, from the default location on the emulator to the /tmp directory on the emulator host machine:
下面是把calc.trace从设备拷贝到电脑/tmp目录的示例:
adb pull /sdcard/calc.trace /tmp
4.在ddms中生成并查看trace文件
4.1在ddms中生成trace文件:
To run Traceview and view the trace files:
- start the Android Device Monitor.
- In the Android Device Monitor tool bar, click DDMS and select a process.
- Click the Start Method Profiling icon to start method profiling.
下图的第6个按钮。(注意第一个是灰色的),按下开始记录,再按下停止记录。
- After the profiling is complete, click the Stop Method Profiling icon to display the traceview.

Note: If you are trying to view the trace logs of an application that is built with ProGuard enabled (release mode build), some method and member names might be obfuscated. You can use the Proguard mapping.txt file to figure out the original unobfuscated names. For more information on this file, see the Proguard documentation.
注意:
ddms生成的trace文件在/tmp下,可以把它拷贝出来然后用dmtracedump生成一个png,
如果的release版或者用 ProGurard优化过的代码,可能有些方法看不到。
5.使用 dmtracedump 工具
5.1about dmtracedump 简介
dmtracedump is a tool that gives you an alternate way of generating graphical call-stack diagrams from trace log files. The tool uses the Graphviz Dot utility to create the graphical output, so you need to install Graphviz before running dmtracedump.
使用 dmtracedump 工具把trace文件中的调用栈按树状显示,在运行 dmtracedump 之前,要先安装 Graphviz。
The dmtracedump tool generates the call stack data as a tree diagram, with each call represented as a node. It shows call flow (from parent node to child nodes) using arrows. The diagram below shows an example of dmtracedump output.
dmtracedump 工具按树状显示方法调用栈的截图如下:

Figure 3. Screenshot of dmtracedump
For each node, dmtracedump shows <ref> callname (<inc-ms>, <exc-ms>,<numcalls>), where
其中每个节点各字段含义如下:
<ref>-- Call reference number, as used in trace logs<inc-ms>-- Inclusive elapsed time (milliseconds spent in method, including all child methods)<exc-ms>-- Exclusive elapsed time (milliseconds spent in method, not including any child methods)<numcalls>-- Number of calls
The usage for dmtracedump is:
dmtracedump的用法如下:
dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-name>
The tool then loads trace log data from <trace-base-name>.data and <trace-base-name>.key. The table below lists the options for dmtracedump.
dmtracedump 命令的各参数如下表:
| Option | Description |
|---|---|
-d <trace-base-name> |
Diff with this trace name |
-g <outfile> |
Generate output to <outfile> |
-h |
Turn on HTML output |
-o |
Dump the trace file instead of profiling |
-d <trace-base-name> |
URL base to the location of the sortable javascript file |
-t <percent> |
Minimum threshold for including child nodes in the graph (child's inclusive time as a percentage of parent inclusive time).If this option is not used, the default threshold is 20%. |
5.2dmtracedump sample示例
- 进入trace文件所在目录
- 运行dmtracedump命令,这里只用了-g参数,-t也很有用。
$dmtracedump 源trace文件 -g 目标图片.png
如:把桌面上的 ddms7018945404796444485.trace 转成 weixin_trace.png
$~/Android/android-sdks/platform-tools/dmtracedump ~/Desktop/ddms7018945404796444485.trace -g ~/Desktop/weixin_trace.png
- 查看生成的文件,其中weixin_trace.png就是生成的方法调用树。
- 打开weixin_trace.png

6.两个bug
- Threads
- Traceview logging does not handle threads well, resulting in these two problems:
- If a thread exits during profiling, the thread name is not emitted (fixed in Android 5.1 and later);
- The VM reuses thread IDs. If a thread stops and another starts, they may get the same ID.
Android 性能优化(24)*性能工具之「Traceview,dmtracedump」Profiling with Traceview and dmtracedump :记录并查看函数调用栈*的更多相关文章
- MYSQL之性能优化 ----MySQL性能优化必备25条
今天,数据库的操作越来越成为整个应用的性能瓶颈了,这点对于Web应用尤其明显.关于数据库的性能,这并不只是DBA才需要担心的事,而这更是我 们程序员需要去关注的事情.当我们去设计数据库表结构,对操作数 ...
- Android开发学习之路--性能优化之常用工具
android性能优化相关的开发工具有很多很多种,这里对如下六个工具做个简单的使用介绍,主要有Android开发者选项,分析具体耗时的Trace view,布局复杂度工具Hierarchy Vie ...
- Android 性能优化 五 性能分析工具dumpsys的使用
Android提供的dumpsys工具能够用于查看感兴趣的系统服务信息与状态,手机连接电脑后能够直接命令行运行adb shell dumpsys 查看全部支持的Service可是这样输出的太多,能够通 ...
- 前端性能优化jQuery性能优化
一.使用合适的选择器 $("#id"); 1.使用id来定位DOM元素无疑是最佳提高性能的方式,因为jQuery底层将直接调用本地方法document.getElementById ...
- Java程序性能优化之性能概述
性能的基本概念 一).什么叫程序的性能? 程序运行所需的内存和时间. 二).性能的表现形式: 1).执行速度: 程序的反应是否迅速,响应时间是否足够短. 2).启动时间:程序从运行到可以处理正常业务所 ...
- Android 性能优化(2)性能工具之「Hierarchy Viewer 」Optimizing Your UI:分析哪个view有性能问题,查看屏幕上某像素点的坐标,颜色等
Optimizing Your UI In this document Using Hierarchy Viewer Running Hierarchy Viewer and choosing a w ...
- Android 性能优化(22)*性能工具之「Hierarchy Viewer」 Hierarchy Viewer Walkthrough
Hierarchy Viewer Walkthrough 1.In this document Prerequisites Setting the ANDROID_HVPROTO variable W ...
- Android性能优化之Systrace工具介绍(一) _&& Systrace生成的trace.html打开空白或者打不开的解决办法
1.必须用Chrome打开 2.在mac电脑上,可能Chrome打开也是空白,解决办法是:在chrome地址栏中输入”chrome:tracing”,然后点击load按钮load你的trace.htm ...
- PLSQL_性能优化效能跟踪工具DBMS_PROFILER分析(案例)
2014-06-01 Created By BaoXinjian
随机推荐
- 【BZOJ3669】魔法森林(LCT)
题意:有一张无向图,每条边有两个权值.求选取一些边使1和n连通,且max(a[i])+max(b[i])最小 2<=n<=50,000 0<=m<=100,000 1<= ...
- 【ZJOI2017 Round1练习&BZOJ5354】D7T3 room(DP)
题意: 思路: 写了两种版本 考场版本 ..,..]of longint; t:..,..]of longint; n,m,i,j,k,oo,ans,d1:longint; function min( ...
- Ajax核心知识(2)
对于Ajax核心的东西需要在进行总结提炼一下: xmlHttp对象. 方法:xml.responseText获取后台传递到前台的数据,经常性的使用var object=xml.responseText ...
- NOIP 2009 潜伏者
P1071 潜伏者 题目描述 RR 国和 SS 国正陷入战火之中,双方都互派间谍,潜入对方内部,伺机行动.历尽艰险后,潜伏于 SS 国的 RR 国间谍小 CC 终于摸清了 SS 国军用密码的编码规则: ...
- Spring Boot实现跨域(转)
一.方法: 服务端设置Respone Header头中Access-Control-Allow-Origin 配合前台使用jsonp 继承WebMvcConfigurerAdapter 添加配置类 二 ...
- Spring 加载类路径外的资源文件
原文:http://blog.csdn.net/gaofuqi/article/details/46417259 <bean id="propertyConfigurer" ...
- python批量删除文件
敲代码測试时总会碰到要删除日志目录下的日志或者删除一些历史文件.每次都会生成,再測试的时候为了查找错误原因方便总是要在測试前删除这些文件.手动删除比較麻烦.所以写一个批量删除脚本 import os ...
- 【Record】ART:Android RunTime
资料来自url=9xdxrhR45Uj3p450JQvTUO-dmzcWswNmABVgYAaFS0AXYDi8Q2JOzvu7y33GIOAI_8Lz7JmLrl0x6DoRW8e5oa" ...
- 浅谈MySQL load data local infile细节 -- 从源码层面
相信大伙对mysql的load data local infile并不陌生,今天来巩固一下这里面隐藏的一些细节,对于想自己动手开发一个mysql客户端有哪些点需要注意的呢? 首先,了解一下流程: 3个 ...
- uva 10452 Marcus
Problem I Marcus, help! Input: standard input Output: standard output Time Limit: 2 Seconds "Fi ...