Android time-consuming analysis (adb shell/Studio CPU Profiler/instrumentation Trace API)

1.adb logcat View cold start time and Activity display time:

Filter the Displayed keyword, and you can see the display time of the Activity.
insert image description here
The time behind the display above refers to the time of which processes are included?

Simulate the operation of sleeping for 1 second in the Application, in the case of cold start:
insert image description here
From the above, we can see that in the case of cold start, the display of the first activity is the total time of cold start=application+Activity time.

Then, click the button on the interface to start an activity at will:
insert image description here
From the above we can see that when the app process is online, the display time of starting the activity is the display time of the activity (onCreate()->onStart()->onResume())

2. The time when the adb shell starts the activity :

format :

adb shell am start -W package名/包名路径的activity

For example, execute and open the specified mainActivity, as shown in the figure below:
insert image description here
Interpret the above data

  • TotalTime: It is the startup time of the Activity, which is consistent with the Display time rule in adb logcat (usually this time prevails)
  • WaitTime: It is the total time for AMS to start the Activity (it will be larger than TotalTime, and there is a cross-process communication receipt time)

Activities started through the adb shell must meet one of the following conditions:

Set the main entry of the program:
insert image description here
or set exported to true
insert image description here

3.AndroidStudio的cpu Profile:

3.1 Applicable to trace capture when the app is cold started :

Create a new running configurations, configure in profiling:
insert image description here
generally choose java method sample, which is the sample mode of Profiler, which has little impact on performance. The system will periodically record the call stack of the java method at intervals of us. The recording is time-consuming and will not be displayed in the trace if it takes less time.

  • Java method trace: It is suitable for accurately recording method execution time, that is, the instrument mode of the profiler. Because it keeps recording the call stack and CPU usage of the method, it has a great impact on performance, and may cause black screens, freezes, etc.
  • CallStack sample is suitable for recording the method analysis of natvie+java, and the sample mode of Profiler.
  • System trace: Record the trace of each system process in the same process, which is suitable for more complex analysis and time-consuming.

How to use: First use the java method sample to record and find out where the time is spent; then use the java method trace to accurately analyze the real time-consuming time.

After clicking the profiler button, after waiting for the installation and startup, the capture will start automatically, and after the process that needs to be observed is executed, click stop.

insert image description here
Open the recorded trace file, select the main main thread, and open it as follows:

insert image description here
From the above, you can clearly see the method call stack and time-consuming of each link in the main thread of the app. The longer the colored square, the more time it takes. Green is generally the code in the app.

Select Application's onCreate() to view, double-click the method, and the following will appear:

insert image description here
From the figure above, we can see that the method takes 1 second from the menu on the left, and the call stack of the method from the top down menu on the right, where the real time-consuming is caused by sleeping for one second.

3.2 When the app is running, record the trace

Some interfaces are triggered under special circumstances of the app to capture the trace of the process. The mobile phone can be connected through usb, and secondly, select the process that can be debugged in the profiler interface, as shown in the figure below:
insert image description here
select cpu, double-click, as shown below:
insert image description here
insert image description here
you can also freely configure the recording conditions, select different cache sizes and cycle time us.

Select the type of trace that needs to be recorded, then use the process in the app, and click stop. For example, open a video page and want to know how long it takes to play, as shown below:

insert image description here
From the top down, it can be clearly seen that the calling time of playing the video testPlay() in the video page.

4. Use the Debug#trace api to accurately record the execution time of the method

The instrumentation method can be used in both release and debug packages, which is more flexible and convenient.

Due to the 8MB buffer space limit, the startMethodTracing(String tracePath) method in the Debug API is designed for scenarios where time intervals are short or it is difficult to manually start/stop recording. To set up longer duration recordings, use the profiler interface in Android Studio.

In short, this method is suitable for app cold start, or for recording trace in a short period of time.

public class TraceMethodUtils {
    
    
    /**
     * 适合于非常精确的记录,某个具体函数的耗时分析
     *
     * profiler cpu 中instrument模式,会从开始一直记录方法/cpu 使用情况,对性能影响大。
     */
    public static void  startTrack(String tracFileName){
    
    
        Debug.startMethodTracing(fixTraceFileName(tracFileName));
    }

    /**
     *  在android 5.0 以后使用,间隔时间微妙 
     *
     *  profiler cpu 中sample模式,系统间隔us 周期性记录调用栈,对性能影响小
     * @param tracFileName
     */
    public static void startSampleTrack(String tracFileName){
    
    
        //1000us=1ms 周期性记录一次
        Debug.startMethodTracingSampling(fixTraceFileName(tracFileName),0,1000);
    }
    private static String fixTraceFileName(String tracFileName){
    
    
        if (!TextUtils.isEmpty(tracFileName)){
    
    
            tracFileName=tracFileName.endsWith(".trace")?tracFileName:tracFileName+".trace";
            tracFileName=new StringBuilder().append(System.currentTimeMillis()).append("_").append(tracFileName).toString();
        }else{
    
    
            tracFileName=new StringBuilder().append(System.currentTimeMillis()).append(".trace").toString();
        }
        return tracFileName;
    }
    /**
     * 结束跟踪
     */
    public static void stopTrack(){
    
    
        Debug.stopMethodTracing();
    }
}

For the analysis of cold start/interface start, it is recommended to use startSampleTrack().

Here, specifically analyze a method testPlay(), execute the method that needs to be recorded, and the records are as follows: the
insert image description here
above file is in the sdcard/android/data/package directory in the DeviceFileExplorer window, double-click to open the trace file, as shown below:
insert image description here
use Method: First select the thread to be viewed, and double-click to enter. Because testPlay() is executed in the main thread, the main thread is selected here:
insert image description here
Bottom UP window

It is used to observe the time-consuming proportion of calling several other methods in a certain method, and can further filter out the specific location of time-consuming, and select the methods with the highest proportion for viewing.
For example, select testPlay() to check the proportion of its internal time-consuming methods: creating a VideoView object takes the most time, 3002us = 3ms milliseconds.

insert image description here

Flame chat flame graph window :

It is used to invert the viewing of calling several methods in a method, and it is very intuitive to see the method calling and time-consuming situation. The light yellow ones are often the method points that need to be paid attention to, and the points that can be optimized are also here.

insert image description here
Top Down window :

It can be used to view, this method goes down the call stack, and you can also clearly see the logic direction of the next code. Also arranged in order of time.

insert image description here
Summary of use: After opening the trace file –> double-click to select the thread –> select the observation method –> the Top Down window refines the time-consuming method –> the Bottom UP window to find the time-consuming point.

Trace storage path and sdcard permission issues

Take a brief look at the save path logic of trace:
insert image description here

It is found that the trace is saved in the sdcard/android/data/package name directory or the sdcard root directory by default, so the sdcard must have read and write permissions. trace will automatically complete the .trace suffix.

Official information: https://developer.android.com/studio/profile/record-traces?hl=zh-cn#debug-api

Information reference :

  • Use of the CPU Profiler system performance analysis tool in Android Studio: https://juejin.cn/post/7098548053136637983
  • https://juejin.cn/post/7024387231104106503
  • TimeTracer, a time-consuming open source analysis tool for Android methods based on AOP ideas: https://www.paincker.com/time-tracer/
  • https://jishuin.proginn.com/p/763bfbd4c428
  • https://zhuanlan.zhihu.com/p/508526020
  • https://juejin.cn/post/7163522788781719559
  • Performance optimization: https://www.jianshu.com/p/837ad55f3049

Guess you like

Origin blog.csdn.net/hexingen/article/details/131936285