Android Drawing Optimization (i) Drawing performance analysis

Source: Internet
Author: User
Tags python script

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.

1.1 rendering the timeline

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.
    • The animation executes too many times at the same time, causing the CPU or GPU to be overloaded.
    • View is over-drawn, causing some pixels to be drawn multiple times within the same frame time.
    • A slightly time-consuming operation 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.

Open a copy of the profile GPU rendering_ copy. png
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:

Here are the meanings of each of them:

    • Swap buffers: Indicates the processing time, as mentioned above in Orange.
    • Command Issue: Indicates the time of execution, as in the red mentioned above.
    • Sync & Upload: Represents the time it takes to prepare an image to be drawn on the current interface, reducing the number of images on the screen or reducing the size of the image in order to reduce the execution time of the area.
    • Draw: Represents the time required to measure and draw a list of views, as in the above mentioned blue.
    • Measure/layout: Represents the time spent in the layout of Onmeasure and OnLayout, and once the time is too long, you need to carefully check your layout for serious performance issues.
    • Animation: Indicates the amount of time it takes to perform an animation, including animations that are objectanimator,viewpropertyanimator,transition, and so on. Once the execution time here is too long, it is necessary to check whether an unofficial animation tool was used or whether it triggered a read-write operation during the execution of the animation, and so on.
    • Input handling: Represents the amount of time the system takes to process an input event, roughly equal to the time it takes to execute the event-handling method. Once the execution time is too long, it means that a complex operation is performed where the user's input events are handled.
    • Misc Time/vsync Delay: Indicates that too many tasks have been performed on the main thread, causing the UI rendering to fall out of the frame without the Vsync signal.

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.

3.1 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.
qq20170311224620_ copy. png

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.py--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:

... PrivateFinal Runnable mupdatechildviewsrunnable =NewRunnable () { Public voidrun () {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 ();    }        }    }; ...
View Code

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.

3.2 Analyzing 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.
Qq20170312150637.png

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 single execution time-consuming method.
    • The number of executions of the method.
4.1 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 ();
View Code

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"/> .

4.2 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 classCoordinatorlayoutactivity extends Appcompatactivity {PrivateViewpager Mviewpager; PrivateTablayout mtablayout; @Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_tab_layout); Debug.startmethodtracing ("Test");//1Initview ();    ...    } Private voidInitview () {Try{Thread.Sleep ( +); } Catch(interruptedexception e) {e.printstacktrace (); }} @Overrideprotected voidOnStop () {super.onstop ();    Debug.stopmethodtracing (); }}
View Code

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 function name called during run of the thread
incl CPU time% A method includes the CPU that is used by the method it calls internally Percentage of
Excl CPU time% A method does not include the percentage of CPU time consumed by methods that it calls internally
incl Real time%< /td> Percentage of real time that a method includes methods that it calls internally
Excl Real time% a method does not include the percentage of real time that the method it calls internally
Calls + recur calls/total Number of methods + recursive calls
Cpu time/call This method Avg. CPU Time
CPU Time/call This method takes up real time on average
incl CPU hours A method includes the CPU time that is consumed by a method that is called internally
Excl CPU Time a method does not include a method that is called internally for CPU duration
in CL Real Time a method that includes the actual duration of the method that it calls internally
Excl Real Time a method does not include the real-world duration of the method it calls internally

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.

  

Android Drawing Optimization (i) Drawing performance analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.