Preface
An excellent application is not only to have attractive features and interactions, but also to have high performance requirements. Mobile phone running Android system, although the configuration in the continuous upgrade, but still can not be compared with the PC, the PC does not have the same large memory and high-performance CPU, so in the development of Android applications can not be unlimited use of CPU and memory, Improper use of CPU and memory can also cause problems such as application lag and memory overflow. As a result, the performance optimization of the application has higher requirements for the developer. Android performance optimization is divided into many kinds, more commonly used in drawing optimization, memory optimization, power consumption optimization and stability optimization, this series we will learn performance optimization in the drawing optimization.
1. Drawing principle
Android draws a view with three main steps, measure, layout, and draw, respectively. See my article on the principles of the Android View System (vii) The measure process and the Android View System (eight) from the source code parsing the view layout and draw process from the source code, here is not to repeat. The measure, layout, and draw methods are primarily run on the application framework layer of the system, while the actual rendering of data to the screen is done by the Surfaceflinger service of the system Nativie layer.
The drawing process mainly consists of CPU measure, Layout, Record, execute data calculation work, GPU is responsible for rasterization, rendering. The CPU and GPU are connected through a graphics-driven layer. The graphics-driven layer maintains a queue in which the CPU adds the display list to the queue so that the GPU can draw the data out of the queue.
Render Timelines
FPS (Frames per Second) This noun I think a lot of classmates know, it refers to the screen transmission frames per second, popular refers to the animation or video screen number, the simplest example is when we play the game, if the screen in 60fps will not feel the lag, if less than 60fps, For example, 50fps will feel the lag, you can consider changing the video card or take some other measures.
To keep the screen at 60fps, you need each drawing to be less than 16ms long, as shown in.
The Android system emits vsync signals every 16ms, triggering the UI rendering, and if each render succeeds, so that the 60fps required for a smooth screen can be reached, what is VSync? VSync is the abbreviation for vertical synchronization (vertical sync), which is a timed interrupt, and once the vsync signal is received, the CPU begins to process each frame of data.
If an operation takes 24ms, the system cannot render properly when the vsync signal is obtained, and a drop frame occurs. The user will see a picture of the same frame in 32ms, as shown in.
There are many reasons for the lag, the main points are as follows:
-Layout layouts are too complex to render within 16MS.
-an excessive number of animations are performed at the same time, resulting in excessive CPU or GPU load.
-View over-drawn, causing some pixels to be drawn multiple times within the same frame time.
-A slightly time-consuming operation is done in the UI thread.
In order to solve the above problems, we can use some tools to analyze and solve the problem of Kaka, except that we should pay attention to writing code.
2.Profile GPU Rendering
The profile GPU rendering is a development aid provided by the Android 4.1 system, and we can open this feature in the developer options as shown in.
We click on the profile GPU rendering option and select on screen as bars to turn on the profile GPU rendering feature. The screen will then display a colored histogram, as shown below.
The horizontal axis of the colored graph above represents the time, and the longitudinal axes represent the duration of a frame. The Green Line is a cordon, more than this line means that the duration of more than 16m, as far as possible to ensure that the vertical color histogram remains below the green lines. These vertical colored histogram stands for a frame, and the color histogram of different colors represents different meanings:
- Orange represents the processing time, where the CPU tells the GPU to render a frame, which is a blocking call because the CPU waits for the GPU to send a reply to the command, and if the orange histogram is high, the GPU is busy.
- Red represents the time of execution, which is part of the time Android renders the Display list in 2D. If the red histogram is high, it may be caused by resubmitting the view. There are also complex custom view that can cause the red histogram to become taller.
- Blue represents the time it takes to measure the drawing, that is, how long it will take to create and update displaylist. If the blue histogram is high, it may need to be redrawn, or the view's OnDraw method handles things too much.
In Android 6.0, there are more colors that are added as shown in:
The profile GPU rendering can find the interface that renders the problem, but if you want to fix it, it's not enough to rely on the profile GPU rendering, you can use another tool hierarchy viewer to see the layout hierarchy and the time each view takes , this tool will be introduced in the next article.
3.Systrace
Systrace is the new performance data sampling and analysis tool in Android4.1. It helps developers to gather operational information for key Android subsystems (Surfaceflinger, Windowmanagerservice, and other framework-critical modules, services, view systems, etc.). The Systrace features include tracking system I/O operations, kernel work queues, CPU load, and the health of various Android subsystems. Analysis data is provided for UI display performance, such as choppy animation, rendering lag, and so on.
using Systrace
Systrace tracking device to the Android4.1 version above, for the Android4.3 version before and after the 4.3 version of the use of a little difference, and now very few people use the previous version of Android4.3, so this is only the Android4.3 version of the use of the method. Systrace can be used on DDMS, can be used on the command line, or can be traced in code. The next step is to introduce these three ways.
using Systrace in Ddms
1. First we want to open Android Device Monitor in the tool of Android studio and connect the phone.
2. Click the Systrace button to enter the crawl Settings screen as shown in.
The crawl settings interface allows you to set the tracking time, as well as the address of the trace file output. As shown in.
3. After the setup is complete, we will be working on the tracking process. After the trace time is over, generate the trace.html file.
4. Use Chrome to open the trace.html file for analysis. The method of analysis, which will be described later.
using Systrace with the command line
Android provides a Python script file systrace.py, which is located in the Android SDK directory/tools/systrace, and we can execute the following command to use Systrace:
$ cd android-sdk/platform-tools/systrace$ python systrace.--time=10-o newtrace.html sched gfx view wm
using Systrace in your code
Systrace does not track all the work of the app, and in the Android4.3 and above versions of the code, you can use the trace class to track specific activities in your app.
The Trace class is also referenced in the Android source code, such as Recyclerview:
...Private final Runnable mupdatechildviewsrunnable = new Runnable () {public void run () {if(!mfirstlayoutcomplete) {return; }if(mdatasethaschangedafterlayout) {tracecompat.beginsection (Trace_on_data_set_change_layout_tag); Dispatchlayout (); Tracecompat.endsection (); }Else if(Madapterhelper.haspendingupdates ()) {tracecompat.beginsection (Trace_handle_adapter_updates_tag); Eatrequestlayout (); Madapterhelper.preprocess ();if(!mlayoutrequesteaten) {rebindupdatedviewholders (); } resumerequestlayout (True); Tracecompat.endsection (); } } };...
The Tracecompat class encapsulates the Trace class, The Trace class will only be used in Android4.3 and above, where the code between the Beginsection method and the Endsection method will be traced, and the Endsection method will only end the nearest Beginsection method, so ensure that the Beginsection party Method and Endsection methods are called the same number of times.
analyze Systrace with chrome
The trace.html generated by the previous method needs to be opened with Chrome, as shown in the post-open effect.
We can use the W key and the S key to zoom in and out, and the A and D keys to move left and right.
Alert Area
First look at the alert area, which marks the point where there is a problem with performance, click the exclamation mark icon to see an alert's problem description, as shown below.
This alert points out that the view spends a lot of time in Measure/layout, causing Jank to appear (multiple times in the same frame). The advice given is to avoid controlling the layout during animation playback.
CPU Area
Next we look at the CPU area, each line represents a CPU core and the time slice that it performs the task, and when zoomed in, you see that each color block represents an executing process, and the length of the color block represents its execution time, as shown in.
In the figure CPU 0 mainly executes ADBB thread and Inputreader thread, CPU 2 mainly executes Surfaceflinger thread and Renderthread thread in ordinatorlayout process, we click Renderthread color block, will give information about the Renderthread, as shown in.
The graph shows information such as the threads and processes that the current color block is running, the opening time and duration, and so on.
application area
The app area displays the number of frames applied, as shown in.
Systrace will give the application of the frames analysis, each frame is an F circle, the F circle has three colors, where green means the frame rendering smooth, yellow and red represents the rendering time of more than 16.6ms, which is more serious red. We click on the red F Circle and will give the frame information as shown in.
As you can see, frame gives the problem hint: Scheduling delay (scheduling delay), when a frame drawing time of more than 19MS will trigger the hint, not to mention that this frame has nearly 40ms. The main reason for this problem is that the thread is not assigned to the CPU time slice for a long time when it is drawn, and therefore cannot continue drawing. Press the M key to highlight the time period, and we'll look at the CPU situation as shown in.
You can see that two CPUs are running at full capacity during this time period. As for what specifically makes the CPU busy, you need to use TraceView for analysis.
Alerts General Analysis
Click the Alerts button on the far right to give a general analysis of the alert, as shown in.
The alerts will give the type of alert and the number of occurrences. With these general analysis, it is convenient for the developer to have a general understanding of the drawing performance of the time period, which facilitates the next analysis.
Since Systrace is returning some information from a system perspective, it can only provide us with an overview, its depth is limited, we can use it for rough checking, in order to understand the approximate situation, but if you want to analyze more detailed, such as to find out what is the CPU busy, the number of calls to some methods, etc., Another tool is also needed: Traceview.
4.Traceview
TraceView is the data acquisition and analysis tool that comes with the Android SDK. Generally speaking, we can get the following two kinds of data through TraceView:
-A time-consuming method for single execution.
-a method that executes many times.
using TraceView
To analyze TraceView, you first want to get a trace file, trace files are obtained in two ways, respectively, in the DDMS and in the code to add debugging statements, the following two methods are described in each.
use in Ddms
1. First we want to open Android Device Monitor in the tool of Android studio and connect the phone.
2. Select the appropriate process and click the Start Method Profiling button.
3. Operate on the points that need to be monitored in the application.
4. Click the Stop Method Profiling button and it will automatically jump to the TraceView view.
adding debug statements to your code
If there is a problem in development that is not reproducible, you need to add the TraceView monitoring statement in your code, as shown in the code below.
Debug.startMethodTracing();...Debug.stopMethodTracing();
Call the Startmethodtracing method where you want to start monitoring, and call the Stopmethodtracing method where you need to end the monitoring. The trace file is generated in the SD card, and the trace file is exported and opened with the TraceView in the SDK. Of course, don't forget to add permissions to the manifest <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
.
Analysis TraceView
To analyze TraceView, let's take a simple example to generate the trace file, which takes the second approach: adding a debug statement to the code. The code is shown below.
Public class coordinatorlayoutactivity extends appcompatactivity { PrivateViewpager Mviewpager;PrivateTablayout mtablayout;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (r.layout.activity_tab_layout); Debug.startmethodtracing ("Test");//1Initview (); ... }Private void Initview() {Try{Thread.Sleep ( +); }Catch(Interruptedexception e) {E.printstacktrace (); } }@Override protected void OnStop() {Super. OnStop (); Debug.stopmethodtracing (); }}
The Startmethodtracing method is called at note 1 to begin monitoring, where test is the name of the generated trace file. In Initview we deliberately call the sleep method to do the time-consuming operation. In the OnStop method we call the Stopmethodtracing method to end the monitoring. The Test.trace file is generated at the root of the SD card, we export the file to the desktop, we parse the Test.trace file with TraceView, and we execute the following statement in CMD.
We enter the directory where TraceView (directly drag traceview.bat into cmd), and execute the TraceView statement will pop up TraceView view, it is divided into two parts, respectively, time-sided Board and analysis Panel, we first look at the time slice panel, as shown in.
where the x-axis represents the consumption of time, the unit is the ms,y axis for each thread. Generally look at the length of the color block, a significantly longer way to focus attention, the specific analysis also depends on the analysis panel, as shown in.
The meaning of the representation of each column of data is shown in the following table.
Column Name |
meaning |
Name |
The name of the function called during the thread's run |
Incl Cpu Time% |
A method includes the percentage of CPU time that is consumed by methods that are called internally |
EXCL Cpu time% |
Percentage of CPU time consumed by a method that does not include the method it calls internally |
Incl Real Time% |
Percentage of real time taken by a method including the method it calls internally |
EXCL Real time% |
Percentage of real time taken by a method that does not include a method of its internal invocation |
Calls + recur Calls/total |
Number of methods + recursive calls |
Cpu Time/call |
This method consumes CPU time on average |
Cpu Time/call |
This method takes up the average real time |
Incl Cpu time |
A method includes the CPU time consumed by the method it calls internally |
EXCL Cpu Time |
A method does not include CPU time consumed by methods that are called internally |
Incl Real time |
A method includes the actual time taken by the method it calls internally |
EXCL Real Time |
A method does not include the actual time taken by the method of its internal invocation |
Because we use the sleep method for time-consuming operations, we can click Incl Real for a descending order. There are many methods of system invocation, and we are going to do one by one filtering. Finally we discovered that the Coordinatorlayoutactivity Initview method incl Real time is 1000.493ms, which is obviously problematic, as shown in.
We can see that it is time consuming to call the sleep method. About TraceView There are many kinds of analysis, you need to accumulate in peacetime.
Well, as for drawing performance analysis, this is the case, and if you don't feel like it, the next article in this series will continue to hit you with a big wave of content.
Resources
"Android Elite Expressive Weapon"
Best Practices for performance optimization for Android applications
http://blog.csdn.net/itachi85/article/details/6857324
Http://www.cnblogs.com/sunzn/p/3192231.html
http://blog.csdn.net/androiddevelop/article/details/8223805
Http://www.tuicool.com/articles/jMfiUjj
Http://www.mobile-open.com/2015/85005.html
Welcome to my public number, the first time to get blog update reminders, and more into the system of Android-related original technology dry.
Sweep the two-dimensional code below or long press identification QR code, you can pay attention to.
Android Drawing Optimization (i) Drawing performance analysis