Practice makes perfect, shortage in play.

Why optimize Cpu utilization?

Optimizing your application’s CPU usage has many benefits, including a faster, smoother user experience and longer battery life on your device.

What are the symptoms caused by low performance?

Common manifestations include long startup time, slow interface switching, page refresh frame, lag, power consumption, and application non-response and program crash.

On the importance of tools

How do we locate performance problems when we encounter performance bottlenecks? If you’re still stuck with visual judgment, multiple replay summary rules, dichotomous code comments remove tests, add log observations, debug breakpoints… This is where qualitative and quantitative analysis comes in… Is can endure ripe cannot endure, loudly shout: I need tool, tool, tool…

Why profiler?

There are many tools for analyzing CPU performance, including TraceView (which profiler has replaced), Profiler, Systrace, and Perfetto (which has replaced Systrace). Don’t worry, there will be a series on… Profilers examine application CPU usage and thread activity in real time as they interact with applications, as well as details of logging method trace data, function trace data, and system trace data. For example, profilers can see which methods were executed by a thread over a period of time, as well as information such as method time and call stack.

Field experience

(1) Practical operation environment

  • Optional, use your own environment and code as well
  • SamplePop code download
  • The SamplePop environment is as follows:

Android Studio 4.0 Gradle Version 6.1.1 Android API Version 30

(2) Open the path

  • View -> Tool Windows -> Profiler
  • You can also Run the program directly and enable profiler monitoring: Run -> profiler

(3) Tool preview

(4) Details page

  • Window 1: It is composed of the following function buttons

Performance category switch button, including CPU, Memeory, Network, and Energy. Select record configuration buttons, including: Sample Java methods, Trace Java methods, sample C/C ++ functions, trace system calls. If you want to learn more about the differences in logging configuration, go directly to the official link at the end of this article. Record start and stop buttons, including: Record, stop.

  • Window 2: set of page adjustment buttons, including: Shrink, enlarge, reset, pause, start, etc.
  • Window 3: Event timeline, which displays different states of the Activity lifecycle, user interaction events, such as click, rotation, and so on.
  • Window 4: CPU timeline, showing real-time CPU usage and the total number of threads currently in use. CPU usage of other processes is also displayed for easy comparison.
  • Window 5: Thread Activity timeline, listing each thread belonging to the application process and indicating their activity on the timeline using the colors listed below.

Green: the thread is active or ready to use the CPU. That is, the thread is in the running or runnable state. Yellow: indicates that the thread is active but is waiting for an I/O operation (such as disk or network I/O). Gray: indicates that the thread is sleeping and does not occupy any CPU time.

(5) Record CPU listening records

During recording, perform some operations to better analyze and find entry points when observing recorded data.

(6) Finish recording

Click the Stop button to finish recording.

  • 1. Selection range: You can drag to select the part of data you want to analyze
  • 2. Interaction events: Display user interaction events, such as click, rotation, etc., as well as life cycle status
  • 3. Application thread: the graph shows the status of user threads. Double-click a specific thread to enter the ** Call chart (reorganization and visual presentation of call stack) ** details of this thread
  • 4. Analyze category labels (If you want to learn more about the differences between category tags, go directly to the official website link at the end of this article) :

TopDown: Summarizes trace information for exactly the same method with the same call stack. Advantages: It’s easy to see the exact amount of time each step took, and sorting by individual dimensions is also very useful for Flame Chart: an inverted call Chart showing aggregated information about the call stack (the Flame Chart TAB provides a graphical representation of the Top Down TAB). Advantages: Easy to find a long call chain BottomUp: Build a tree from the bottom and work backwards. Advantage: Easy to find the call stack for a method

  • 5. Filters: Search filtering, matchCase is case-sensitive, and Regex uses regular expressions
  • 6. Event type: Wall Clock Time Actual elapsed Time, Thread Time consumed CPU Time

(6.1) Clarification (only for old version users) Well, here, it is estimated that some people have some doubts, this is not the same as my recording results ah, at least the appearance has changed… Where did the time stamp go? Where did Call Chart go? Before the vertical layout display, now how is the whole left and right split screen display? why? Whoa, whoa, whoa, whoa, whoa, whoa, whoa, whoa, whoa, whoa, whoa, whoa, whoa, whoa, whoa. First question: why are all the looks changed? Because I’m using AndroidStudio 4.0. If you like the new style, just update it. Second question: Where did the time stamp go? In fact, the time stamp is still there, but before the absolute time stamp, now the relative time is wrong, for example, when recording 10 seconds, the time stamp is from 0s -> 10s. Third question: What about Call Chart? Now what is left and right split screen display? Because the new version of the classification TAB page has been optimized. In previous versions, did you struggle with the frequent switching between Call Chart and other tabs? Are you struggling with what you’re doing while recording? … The following new version of the new features for you to answer. New features in the new version: 1. The previous Event pane is displayed, and the Interaction pane is replaced (subdivided for Interaction events, which is intuitive and convenient to view) 2. Aggregate the information of the Call Chart analysis window and Threads window. Select one of the specific Threads Windows (such as Main) and double-click to enter it. You will find the Call Chart analysis window inside. Can call chart with other three analysis category (TopDown/FlameChart/BottomUp) linkage data analysis, this is my favorite place.

(7) Analysis

Sample code for SamplePop:

(7.2) Call Chart

When no specific method is selected, each method will be one of three colors:

  • Green: Calls that apply their own methods
  • Blue: calls to third-party apis (including Java language apis)
  • Orange: System API calls

(7.3) Flame Chart

You can see at a glance which method takes the longest total time, and then either try to solve it step by step (in SamplePop, it’s obvious that you’re doing log printing in a loop, consuming a lot of CPU).

(7.4) Top Down

Any surprise? Like Flame Chart above, the log function consumes 49.5% of the CPU for this method, but flame Chart is a little more intuitive.

I’ve Bottom Up

So, is the sound still there? And from the default sort, you can see which method consumes the most CPU. In fact, the three categories show problems in different ways, each has its own advantages, appropriate choice can be.

(7.6) Minimalist mode

Above analysis, are from a simple example to tell the use of tools, convenient for everyone to understand. As long as you master the basic tools and analysis methods, and then through the actual use of the project, I believe that you will be able to solve various problems with ease. Did you think it was over? There’s no…

(8) Start the node to enable recording

Log CPU activity during application startup.

(8.1) The hand is never as fast as the machine, and it is entirely up to it to analyze the startup process of the application

(8.2) Then Run -> Profiler starts the application (once the application is started, CPU data tracing is enabled). The following is the data generated after the application is started:

(9) Debug API records

Use the Debug API to log CPU activity.

(9.1) When not satisfied with the above positioning and analysis methods, you also want to:

  • Precisely controls when the device starts and stops recording trace information
  • The device can save trace logs with the names you specify, making it easy for you to identify individual log files later

Then you deserve the Debug API.

Then use adb command to pull out the trace file:

  • The adb pull/sdcard/Android/data/com kejiyuanren. Pop/files/kejiyuanren trace. (this. Represents the path of the current command window.
  • Import the trace file using the Android profiler (Sessions window has import button)

(9.3) Is the Debug API useful? But there are a few things to note:

  • The website says that using the Debug API requires external storage permissions, but my project works without them (awkward, probably because I’m using the new version).
  • This method will slow down the application speed. You can confirm whether the optimization is effective by comparing the time consumption before and after optimization
  • The name of the trace file must be changed or it will be overwritten

Xiaobian extension links

  • SamplePop code download
  • Android Performance Optimization family Bucket

Refer to the link

  • This is the first article that should be read
  • Google Developers -> This is the best article for an in-depth understanding of the principles of the four tabs
  • Great post -> This is a great post to look at tool usage in detail

It’s finally over. Have a good laugh

❤ ❤ than heart