Monitoring CPU, Memory, and Network with Android Studio Profiler

Monitoring CPU, Memory, and Network with Android Studio Profiler

Hacker Techniques
Click on the right to follow and understand the world of hackers!
Monitoring CPU, Memory, and Network with Android Studio Profiler

Monitoring CPU, Memory, and Network with Android Studio Profiler

Java Development Progress
Click on the right to master the advanced path!
Monitoring CPU, Memory, and Network with Android Studio Profiler

Monitoring CPU, Memory, and Network with Android Studio Profiler

Python Development
Click on the right to discuss technical topics!
Monitoring CPU, Memory, and Network with Android Studio Profiler
Author丨Android Da Qiang GeSource丨Jianshu
Link:
https://www.jianshu.com/p/0770cde09ede
This tutorial is a simplified version of the official tutorial, extracting the essentials from the official guide. Additionally, an example of analyzing memory leaks is included.
The Android Profiler provides real-time data on your app’s CPU, memory, and network usage.
Monitoring CPU, Memory, and Network with Android Studio Profiler
Table of Contents

1 Start Analysis

To open the Android Profiler window, follow these steps:
1. Click on Android Profiler in the toolbar (you can also click View > Tool Windows > Android Profiler).
2. Select the device and app process you want to analyze at the top of the Android Profiler window, as shown in the image below.
Monitoring CPU, Memory, and Network with Android Studio Profiler
Android Profiler window
The meanings of the various numbers in the image above are:
① Device to analyze.
② App process to analyze.
③ Timeline zoom control.
④ Real-time update jump button.
⑤ Event timeline, including Activity status, user input events, and screen rotation events.
If “Advanced profiling is unavailable for the selected process” is displayed, you can click Profile ‘app’ in the top toolbar to run it, or enable advanced profiling in the run configuration by following these steps:
1. Select Run > Edit Configurations.
2. Select your application module in the left pane.
3. Click on the Profiling tab and check Enable advanced profiling.
Rebuild and run the application.

2 CPU Profiler

The CPU Profiler helps to check the app’s CPU usage and thread activity in real-time and records function traces for optimizing and debugging app code.

2.1 CPU Profiler Overview

Monitoring CPU, Memory, and Network with Android Studio Profiler
CPU Profiler Overview
As shown in the image above, the default view of the CPU Profiler includes the following:
① Event timeline: Shows the Activities transitioning in your app during its lifecycle and displays user interactions with the device, including screen rotation events.
② CPU timeline: Displays the app’s real-time CPU usage (as a percentage of total available CPU time) and the total number of threads used by the app. This timeline also shows the CPU usage of other processes (such as system processes or other apps), allowing you to compare it with your app’s usage. By moving the mouse along the horizontal axis of the timeline, you can also inspect historical CPU usage data.
③ Thread activity timeline: Lists each thread belonging to the app process. Below is an explanation of the meaning of different colors:
  • Green: Indicates that the thread is active or ready to use the CPU. That is, it 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) to complete its work.
  • Gray: Indicates that the thread is sleeping and is not consuming any CPU time. This can occasionally happen when a thread needs to access a resource that is not yet available. The thread may enter a self-sleep state or the kernel may put this thread to sleep until the required resource is available.
④ Recording configuration: Select how the profiler records function traces, as follows:
  • Sampled: Records at fixed intervals. Frequently captures the call stack of the app during execution. The profiler compares the captured datasets to deduce time and resource usage information related to the execution of the app’s code. The problem with “Sampled” tracing is that if the app enters a function after capturing the call stack and exits that function before the next capture, the profiler will not record that function call. If you are interested in tracking such short-lived functions, you should use “Instrumented” tracing.
  • Instrumented: Records based on the time of function calls. It sets the app to record timestamps at the start and end of each function call during runtime. It collects timestamps and compares them to generate function trace data, including timing information and CPU usage. Note that the overhead associated with setting this up for each function will impact runtime performance and may affect the analysis data, especially for functions that are relatively short-lived. Additionally, if the app executes a large number of functions in a short time, the profiler may quickly exceed its file size limit and will not be able to record more trace data.
  • Edit configurations: Allows you to change certain default values for the above “Sampled” and “Instrumented” recording configurations and save them as custom configurations.
⑤ Record button: Used to start and stop recording function traces.
Note: The profiler will also report the CPU usage of threads that Android Studio and the Android platform add to your app process (such as JDWP, Profile Saver, Studio:VMStats, Studio:Perfa, and Studio:Heartbeat).

2.2 Recording and Inspecting Function Traces

Select Sampled or Instrumented, then click Record to start recording function traces, and click Stop recording to end, as shown in the image below.
Monitoring CPU, Memory, and Network with Android Studio Profiler
Recording and Inspecting Function Traces
① Select Time Range: Determine which part of the recorded time range to inspect in the tracing pane. When function tracing is first recorded, the CPU Profiler will automatically select the full length in the CPU timeline. If you want to check only a small part of the recorded time range for function trace data, you can click and drag the edges of the highlighted area to modify its length.
② Timestamps: Used to indicate the starting and ending times of the recorded function traces (relative to the time the profiler started collecting CPU usage information from the device). You can click the timestamp to automatically select the full record.
③ Tracing Pane: Displays the function trace data for the selected time range and thread.
Displays function trace data in the form of call graphs, flame graphs, Top Down trees, or Bottom Up trees.
Determines how to measure the timing information for each function call:
  • Wall clock time: Actual elapsed time.
  • Thread time: Actual elapsed time minus the time the thread did not consume CPU resources.

2.2.1 Inspecting Traces Using Call Chart Tab

The Call Chart tab provides a graphical representation of function traces, where the horizontal axis represents the time of function calls (or callers), and the vertical axis displays their callees. Function calls to system APIs are shown in orange, calls to application-specific functions are shown in green, and calls to third-party APIs (including Java language APIs) are shown in blue. The image below shows an example of a call chart and depicts the concepts of Self time, Children time, and total time for a given function.

Monitoring CPU, Memory, and Network with Android Studio Profiler
Inspecting Traces Using Call Chart Tab
Tip: To jump to the source code of a function, right-click on that function and select Jump to Source.

2.2.2 Inspecting Traces Using Flame Chart Tab

The Flame Chart tab provides an inverted call chart, where the horizontal axis no longer represents the timeline but instead indicates the relative execution time of each function.
To illustrate this concept, consider the call chart below. Note that function D calls B multiple times (B1, B2, and B3), some of which also call C (C1 and C3).
Monitoring CPU, Memory, and Network with Android Studio Profiler
Inspecting Traces Using Flame Chart Tab
Since B1, B2, and B3 share the same caller sequence (A → D → B), they can be aggregated together as shown below. Similarly, C1 and C3 can be aggregated together because they also share the same caller sequence (A → D → B → C). Note that C2 is not included because it has a different caller sequence (A → D → C).
Monitoring CPU, Memory, and Network with Android Studio Profiler
The aggregated function calls are used to create the flame graph, as shown in the image below. Note that for any given function call in the flame graph, the callee that consumes the most CPU time is shown first.
Monitoring CPU, Memory, and Network with Android Studio Profiler

2.2.3 Inspecting Traces Using Top Down and Bottom Up

Top Down tab displays a list of function calls, where expanding a function node shows its callees. The image below shows the “Top Down” chart corresponding to the above call chart. Each arrow in the chart points from the caller to the callee.
Monitoring CPU, Memory, and Network with Android Studio Profiler
(Top Down(How big! Can anyone teach me how to scale the image?)
As shown in the image above, expanding the node of function A in the “Top Down” tab reveals its callees, which are functions B and D. Then, expanding the node of function D shows its callees, which include functions B and C, and so on.
The Top Down tab provides the following information to illustrate the CPU time spent on each function call:
  • Self: Indicates the time spent by the function call executing its own code (rather than the code of callees).
  • Children: Indicates the time spent by the function call executing its callees (rather than its own code).
  • Total: The sum of the Self and Children time for the function. Indicates the total time the application spent executing the function call.
Bottom Up tab displays a list of function calls, where expanding a function node shows its callers, as shown in the image below.
Monitoring CPU, Memory, and Network with Android Studio Profiler
Bottom Up(How big! Can anyone teach me how to scale the image?)
As shown in the image above, when opening the node of function C in the “Bottom Up” tree, it reveals its callers B and D. Note that although B calls C twice, when expanding the node of function C in the “Bottom Up” tree, B only appears once. Then, expanding the node of B shows its callers, which are functions A and D.
Note: When the profiler reaches the file size limit, Android Studio will stop collecting new data (but will not stop recording).

2.3 Creating Recording Configurations

To create or edit custom configurations or check existing default configurations, you can open the CPU Recording Configurations dialog by selecting Edit configurations from the recording configuration dropdown menu, as shown in the image below.
Monitoring CPU, Memory, and Network with Android Studio Profiler
Creating Recording Configurations
You can select existing configurations in the left pane to check their settings, or create a new recording configuration as follows:
1. Click the ➕ in the upper left corner of the dialog.
2. Name the configuration.
3. In the Trace Technology section, select Sampled or Instrumented.
4. For “Sampled” recording configurations, specify the Sampling interval in microseconds (μs). This value indicates the duration between each sampling of the application’s call stack.
5. For the data written to the connected device, specify the File size limit in megabytes (MB). When you stop recording, Android Studio will parse this data and display it in the profiler window.
Note: If you are using a connected device running API level 26 or higher, there is no limit on the file size for tracing data, and this value can be ignored.
6. Click Apply or OK. If you changed any other recording configurations, those changes will also be saved.

3 Memory Profiler

The Memory Profiler helps identify memory leaks and losses that cause the app to stutter, freeze, or even crash. It displays a real-time chart of the app’s memory usage, can capture heap dumps, enforce garbage collection, and track memory allocations.

3.1 Memory Profiler Overview

Monitoring CPU, Memory, and Network with Android Studio Profiler
Memory Profiler Overview
As shown in the image above, the default view of the Memory Profiler includes the following:
① Enforce garbage collection event.
② Capture heap dump.
③ Record memory allocations. This button only appears when running on devices with Android 7.1 or lower.
④ Zoom in/out of the timeline.
⑤ Jump to real-time memory data.
⑥ Event timeline, showing Activity state, user input events, and screen rotation events.
⑦ Memory usage timeline, containing the following:
  • Displays a stacked graph of how much memory is used by each memory category, as shown on the left y-axis and the colored key at the top.
  • The dashed line indicates the number of allocated objects, as shown on the right y-axis.
  • Icons representing each garbage collection event.
Monitoring CPU, Memory, and Network with Android Studio Profiler
As shown in the image, the categories in memory counts are as follows:
  • Java: Memory allocated for objects from Java or Kotlin code.
  • Native: Memory allocated for objects from C or C++ code.
  • Graphics: Memory used by graphics buffers to display pixels on the screen (including GL surfaces, GL textures, etc.). (Note that this is memory shared with the CPU, not dedicated GPU memory.)
  • Stack: Memory used by native and Java stacks in the application, usually related to how many threads the application is running.
  • Code: Memory used by the application to process code and resources (such as dex bytecode, optimized or compiled dex code, .so libraries, and fonts).
  • Other: Memory used by the application that the system cannot categorize.
  • Allocated: The number of Java/Kotlin objects allocated by the application. Objects allocated in C or C++ are not counted.
Note: Currently, the Memory Profiler also reports some false positives for native memory usage in the application, which is actually used by the analysis tools. For about 100,000 objects, this can increase the reported memory usage by up to 10MB.

3.2 Viewing Memory Allocations

The Memory Profiler can display the following information about object allocations:
  • What types of objects are allocated and how much space they use.
  • The stack trace for each allocation, including which thread it was allocated in.
  • When objects are deallocated (Android 8.0+).
If the device is running Android 8.0 or higher, you can view object allocations as follows: simply click and hold the timeline and drag to select the area you want to view allocations for.
If the device is running Android 7.1 or lower, click Record memory allocations in the Memory Profiler toolbar. After the operation is complete, click Stop recording to view the allocations, as shown in the image below:
Monitoring CPU, Memory, and Network with Android Studio Profiler
After selecting a time range on the timeline, the list of allocated objects will be displayed below the timeline, grouped by class name and sorted by heap count.
Note: On Android 7.1 and lower, a maximum of 65,535 allocations can be recorded. If the recording exceeds this limit, only the latest 65,535 allocations will be kept in the recording. On Android 8.0 and higher, there is no such limit.
To inspect the allocation records, follow these steps:
1. Browse the list to find objects with unusually large heap counts that may indicate leaks. Clicking the Class Name column header will sort them alphabetically. Then click on a class name. The Instance View pane will appear on the right, showing each instance of that class.
2. In the Instance View pane, click on an instance. The Call Stack tab will appear below, showing where that instance was allocated and in which thread, as shown in the image below.
3. In the Call Stack tab, double-click any line to jump to that code in the editor.
Monitoring CPU, Memory, and Network with Android Studio Profiler
By default, the allocation list on the left is arranged by class name. At the top of the list, you can switch between the following arrangements using the dropdown on the right:
  • Arrange by class: Groups all allocations by class name.
  • Arrange by package: Groups all allocations by package name.
  • Arrange by callstack: Groups all allocations by their corresponding call stacks.

3.3 Capturing Heap Dumps

Heap dumps show which objects in the application are using memory at the time of capture. Particularly after long user sessions, heap dumps can reveal objects that you believe should no longer be in memory but still are, helping to identify memory leaks. After capturing a heap dump, you can view the following information:
  • What types of objects have been allocated by the application and how many have been allocated for each type.
  • How much memory each object is using.
  • Where in the code each object is still referenced.
  • The call stack where the object was allocated. (Currently, if a heap dump is captured while recording allocations, the call stack can only be used in Android 7.1 and lower.)
To capture a heap dump, click Dump Java heap in the Memory Profiler toolbar. During the heap dump, the amount of Java memory may temporarily increase, which is normal, as the heap dump occurs in the same process as your application and requires some memory to collect the data.
The heap dump is displayed below the memory timeline, showing all class types in the heap, as shown in the image below.
Monitoring CPU, Memory, and Network with Android Studio Profiler
Heap Dump
To inspect the heap, follow these steps:
1. Browse the list to find objects with unusually large heap counts that may indicate leaks. Clicking the Class Name column header will sort them alphabetically. Then click on a class name. The Instance View pane will appear on the right, showing each instance of that class.
2. In the Instance View pane, click on an instance. The References tab will appear below, showing each reference to that object. You can click the arrow next to the instance name to see all its fields, and then click a field name to view all its references. If you want to see details of an instance for a particular field, right-click that field and select Go to Instance, as shown in the image below.
3. In the References tab, if you find a reference that may leak memory, right-click it and select Go to Instance.
Monitoring CPU, Memory, and Network with Android Studio Profiler
In the class list, you can view the following information:
  • Heap Count: The number of instances in the heap.
  • Shallow Size: The total size of all instances in this heap (in bytes).
  • Retained Size: The total size of memory retained for all instances of this class (in bytes).
At the top of the class list, you can switch between the following heap dumps using the left dropdown:
  • Default heap: When the system does not specify a heap.
  • App heap: The main heap where the application allocates memory.
  • Image heap: The system startup image that contains classes preloaded during startup. Allocations here are guaranteed to never move or disappear.
  • Zygote heap: A copy-on-write heap from which application processes are derived from the Android system.
By default, this list is sorted by Retained Size, and you can click any column header to change the sorting order of the list.
In the Instance View, each instance contains the following information:
  • Depth: The shortest number of hops from any GC root to the selected instance.
  • Shallow Size: The size of this instance.
  • Retained Size: The size of memory dominated by this instance.

3.4 Saving Heap Dumps as HPROF

If you want to save a heap dump for later viewing, you can export the heap dump to an HPROF file by clicking Export heap dump as HPROF file in the toolbar below the timeline. In the dialog that appears, be sure to save the file with the .hprof suffix. You can then open this file in Android Studio by dragging it into an empty editor window.
To use other HPROF analyzers (such as jhat), you need to convert the HPROF file from Android format to Java SE HPROF format. You can use the hprof-conv tool in the android_sdk/platform-tools/ directory to do this. Running the command requires two parameters: the original HPROF file and the write location for the converted HPROF file. For example:
hprof-conv heap-original.hprof heap-converted.hprof

3.5 Analyzing Memory Leak Example

The following example illustrates how to analyze a memory leak.
The image below shows the entry into an Activity that causes a memory leak, and below it demonstrates how to find the class that causes the memory leak using the Memory Profiler and locate the leaking code.
Monitoring CPU, Memory, and Network with Android Studio Profiler
Analyzing Memory Leak Example (Oh my, it’s really big…)
First, we can repeatedly enter and exit the memory leak Activity, then force garbage collection in the Memory Profiler, and finally capture a heap dump. After the analysis results come out, we can click the filter button on the right to filter the package name we are concerned about, as shown in the image below:
Monitoring CPU, Memory, and Network with Android Studio Profiler
You can also choose to select “Arrange by package” at “Arrange by class” for manual selection.
We can see three MemoryLeakActivity objects, which theoretically should not remain in memory after exiting and GC. We click on that row, and the right side displays each instance. Clicking on one instance shows its references, as shown in the image below:
Monitoring CPU, Memory, and Network with Android Studio Profiler
We can double-click the first reference, or right-click and choose “Jump to Source” to locate the code that causes the memory leak, as shown below:
Monitoring CPU, Memory, and Network with Android Studio Profiler
Code that Causes Memory Leak
This concludes the analysis process of a memory leak.

4 Network Profiler

The Network Profiler can display real-time network activity on the timeline, including data sent and received and the current number of connections, making it easy to see how and when the application transmits data and optimize the underlying code accordingly.

4.1 Network Profiler Overview

Monitoring CPU, Memory, and Network with Android Studio Profiler
Network Profiler Overview
As shown in the image above, the top of the window displays the event timeline and the comparison of wireless device power status (low/high) with WLAN①. On the timeline, you can click and drag to select a portion of the timeline to inspect network traffic②. The lower window③ will display the files sent and received within the selected segment of the timeline, including file names, sizes, types, statuses, and times. You can sort by clicking any column header. Additionally, you can view detailed data for the selected segment of the timeline, showing the send and receive times for each file.
Clicking on the name of a network connection will allow you to view details about the selected file that was sent or received④. You can view response data, header information, and call stacks by clicking on various tabs.
Note: The Network Profiler currently only supports HttpURLConnection and OkHttp network connection libraries.

References

  1. https://developer.android.com/studio/profile/android-profiler

  2. https://blog.csdn.net/niubitianping/article/details/72617864

  3. https://blog.csdn.net/Double2hao/article/details/78784758

Recommended↓↓↓

Monitoring CPU, Memory, and Network with Android Studio Profiler

Long

Press

Close

Note

👉16 Technical Public Accounts】 are all here!

Covers: Programmer big shots, source code reading, programmer reading, data structures and algorithms, hacker techniques and network security, big data technology, front-end programming, Java, Python, web programming development, Android, iOS development, Linux, database development, humorous programmers, etc.

^No matter how far apart, there is always affection, can you give a “look“?

Leave a Comment

×