Android 性能优化(24)*性能工具之「Traceview,dmtracedump」Profiling with Traceview and dmtracedump :记录并查看函数调用栈*...

mac2022-07-01  15

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 stoppedA 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 Debug class in your code and call its methods such as startMethodTracing() and stopMethodTracing(), 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 Debug class, 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.

  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文件很大,可以只对感兴趣的代码记录。

 

1 // start tracing to "/sdcard/calc.trace" 2 Debug.startMethodTracing("calc"); 3 // ... 4 // stop tracing 5 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 <refcallname (<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 命令的各参数如下表: OptionDescription-d <trace-base-name>Diff with this trace name-g <outfile>Generate output to <outfile>-hTurn on HTML output-oDump 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.

 

 

转载于:https://www.cnblogs.com/sjjg/p/5421616.html

最新回复(0)