1e41f4b71Sopenharmony_ci# Typical Traces
2e41f4b71Sopenharmony_ci
3e41f4b71Sopenharmony_ci## Introduction
4e41f4b71Sopenharmony_ci
5e41f4b71Sopenharmony_ciThe DFX subsystem provides performance traces for the application framework and core modules of the system. Each trace records the task execution time, formatted data at runtime, and process or thread information. You can use [Smartperf-Host](../../device-dev/device-test/smartperf-host.md) to parse the traces, analyze the performance hotspots during application running based on the trace lanes, and work out a performance optimization solution.
6e41f4b71Sopenharmony_ci
7e41f4b71Sopenharmony_ciThis topic describes the meanings and usage of typical traces, and demonstrates how to use them to identify potential performance problems. It also elaborates the working principles of traces to help you better collect and analyze performance data. An in-depth understanding of traces will provide considerable support for your application performance profiling.
8e41f4b71Sopenharmony_ci
9e41f4b71Sopenharmony_ci## Typical Traces and Their Meanings
10e41f4b71Sopenharmony_ci
11e41f4b71Sopenharmony_ciThe following describes typical traces in the rendering process.
12e41f4b71Sopenharmony_ci
13e41f4b71Sopenharmony_ci### Rendering Process
14e41f4b71Sopenharmony_ci
15e41f4b71Sopenharmony_ciLike other operating systems, OpenHarmony uses the Vsync signal to determine the time to render a frame. The Vsync signal, short for vertical sync signal, instructs the display to start refreshing the next frame after the vertical blanking interval.
16e41f4b71Sopenharmony_ci
17e41f4b71Sopenharmony_ciThe display sends the Vsync signal at a fixed frequency. For example, if the refresh rate is 60 Hz, the display sends the Vsync signal every 16.6 ms.
18e41f4b71Sopenharmony_ci
19e41f4b71Sopenharmony_ciUpon receiving the Vsync signal, the UI backend engine prepares for rendering of the next frame. Then the application submits a rendering command, which is used to describe graphics rendering, texture setting, and shader usage. The UI backend engine adds the command to the rendering queue and executes the command at a proper time. Generally, the rendering command is executed in the background thread to prevent the main thread from being blocked.
20e41f4b71Sopenharmony_ci
21e41f4b71Sopenharmony_ciAfter finishing the command execution, the UI backend engine sends it to Render Service of the graphics subsystem. Render Service performs graphics calculation and rendering operations, such as vertex transformation, illumination, and texture mapping. After Render Service finishes rendering, it writes the rendering result to the frame buffer. The frame buffer is a memory area that stores image data for display output. Once the frame buffer is updated, the UI backend engine waits for the next Vsync signal. This ensures that the rendering result is ready before the vertical blanking interval elapses. When the next Vsync signal arrives, the UI backend engine sends the content in the frame buffer to the display, and the display refreshes its pixels accordingly. Till now, the rendering process is complete. See Figure 1.
22e41f4b71Sopenharmony_ci
23e41f4b71Sopenharmony_ci**Figure 1 Rendering flowchart**
24e41f4b71Sopenharmony_ci
25e41f4b71Sopenharmony_ci![Rendering flowchart](figures/trace-process.jpg)
26e41f4b71Sopenharmony_ci
27e41f4b71Sopenharmony_ciFrom the perspective of traces, the rendering process for a frame is as follows:
28e41f4b71Sopenharmony_ci
29e41f4b71Sopenharmony_ci(1) A Vsync signal arrives.
30e41f4b71Sopenharmony_ci
31e41f4b71Sopenharmony_ci(2) The UI backend engine draws the first frame.
32e41f4b71Sopenharmony_ci
33e41f4b71Sopenharmony_ci(3) The UI backend engine sends a rendering command to Render Service and requests a frame.
34e41f4b71Sopenharmony_ci
35e41f4b71Sopenharmony_ci(4) Render Service composites graphics layers, calculates the region to refresh, and renders and draws the frame.
36e41f4b71Sopenharmony_ci
37e41f4b71Sopenharmony_ci(5) Render Service sends the drawn frame to the display.
38e41f4b71Sopenharmony_ci
39e41f4b71Sopenharmony_ciFigure 2 shows typical traces used by the UI backend engine in the rendering process of a frame.
40e41f4b71Sopenharmony_ci
41e41f4b71Sopenharmony_ci**Figure 2** Trace lanes for UI backend engine rendering
42e41f4b71Sopenharmony_ci
43e41f4b71Sopenharmony_ci![Trace lanes for UI backend engine rendering](figures/trace-ui-engine.png)
44e41f4b71Sopenharmony_ci
45e41f4b71Sopenharmony_ci| No. | **Trace**                               | **Parameter Description**        | **Process Description**                              |
46e41f4b71Sopenharmony_ci|:--- | --------------------------------------- | ---------------- | ------------------------------------ |
47e41f4b71Sopenharmony_ci| 1   | OnVsyncEvent now:%" PRIu64 "            | Current timestamp, in nanoseconds.      | Receives a Vsync signal. The rendering process starts.                    |
48e41f4b71Sopenharmony_ci| 2   | FlushVsync                              |                  | Refreshes the view synchronization events, including recording frame information, refreshing tasks, drawing and rendering the context, and processing user input.|
49e41f4b71Sopenharmony_ci| 3   | UITaskScheduler::FlushTask              |                  | Refreshes the UI, including the layout, rendering, and animation.                  |
50e41f4b71Sopenharmony_ci| 4   | FlushMessages                           |                  | Sends a message to instruct Render Service to perform rendering.                       |
51e41f4b71Sopenharmony_ci| 5   | FlushLayoutTask                         |                  | Executes the layout task.                              |
52e41f4b71Sopenharmony_ci| 6   | FlushRenderTask %zu                     | Number of nodes to be rendered on the current page.| Executes the rendering task.                             |
53e41f4b71Sopenharmony_ci| 7   | Layout                                  |                  | Lays out the nodes.                                |
54e41f4b71Sopenharmony_ci| 8   | FrameNode::RenderTask                   |                  | Executes a single rendering task.                            |
55e41f4b71Sopenharmony_ci| 9   | ListLayoutAlgorithm::MeasureListItem:%d | Index of the current list item.         | Calculates the layout size of the list item.                          |
56e41f4b71Sopenharmony_ci
57e41f4b71Sopenharmony_ciRender Service in the graphics subsystem is responsible for drawing UI content, processing rendering tasks submitted by applications, combining graphics layers of different applications, and presenting images on the display.
58e41f4b71Sopenharmony_ci
59e41f4b71Sopenharmony_ciWhen receiving a Vsync signal, the UI backend engine processes the command sent by the application, including adding, deleting, or modifying the application's render node, and then performs animation calculation and occlusion calculation. All these operations are used to update the render tree.
60e41f4b71Sopenharmony_ci
61e41f4b71Sopenharmony_ciThe UI backend engine draws the render tree. Specifically, it preprocess every node, calculates the absolute position and dirty region, and draws the dirty region. It preferentially uses the hardware composer for drawing. If certain content cannot be composited, the GPU performs redrawing. All the drawing results are stored in the display buffer and finally presented on the display.
62e41f4b71Sopenharmony_ci
63e41f4b71Sopenharmony_ciFigure 3 shows the trace lanes when the Vsync signal is refreshed.
64e41f4b71Sopenharmony_ci
65e41f4b71Sopenharmony_ci**Figure 3** Trace lanes on Render Service
66e41f4b71Sopenharmony_ci
67e41f4b71Sopenharmony_ci![Trace lanes on Render Service](figures/trace-rs.png)
68e41f4b71Sopenharmony_ci
69e41f4b71Sopenharmony_ci| No. | Trace                        | Description          |
70e41f4b71Sopenharmony_ci|:--- | ---------------------------- | ------------ |
71e41f4b71Sopenharmony_ci| 1   | RSMainThread::DoComposition  | Composites the layers of nodes in the render tree. |
72e41f4b71Sopenharmony_ci| 2   | RSMainThread::ProcessCommand | Processes the command from the client. |
73e41f4b71Sopenharmony_ci| 3   | Animate                      | Processes the animation.        |
74e41f4b71Sopenharmony_ci| 4   | RSMainThread::CalcOcclusion  | Calculates the occlusion.        |
75e41f4b71Sopenharmony_ci| 5   | ProcessDisplayRenderNode[x]  | Performs drawing on a single display.|
76e41f4b71Sopenharmony_ci| 6   | ProcessSurfaceNode:x         | Performs composition on a single node.  |
77e41f4b71Sopenharmony_ci| 7   | Repaint                      | The hardware composer performs composition.   |
78e41f4b71Sopenharmony_ci| 8   | Redraw                       | Redraws the image if certain content cannot be composited.|
79e41f4b71Sopenharmony_ci| 9   | RenderFrame                  | The GPU performs drawing.     |
80e41f4b71Sopenharmony_ci| 10  | SwapBuffers                  | Refreshes the display buffer.     |
81e41f4b71Sopenharmony_ci| 11  | Commit                       | Presents the drawing result on the display.    |
82e41f4b71Sopenharmony_ci
83e41f4b71Sopenharmony_ci### Lazy Loading
84e41f4b71Sopenharmony_ci
85e41f4b71Sopenharmony_ciLazy loading is implementing using **LazyForEach**, which iterates over provided data sources and creates corresponding components during each iteration. When **LazyForEach** is used in a scrolling container, the framework creates components as required within the visible area of the scrolling container. When a component is out of the visible area, the framework destroys the component to reduce memory usage.
86e41f4b71Sopenharmony_ci
87e41f4b71Sopenharmony_ciFigure 4 shows the traces for a frame during lazy loading.
88e41f4b71Sopenharmony_ci
89e41f4b71Sopenharmony_ci**Figure 4** Trace lanes for lazy loading
90e41f4b71Sopenharmony_ci
91e41f4b71Sopenharmony_ci![Trace lanes for lazy loading](figures/trace-lazyforeach.png)
92e41f4b71Sopenharmony_ci
93e41f4b71Sopenharmony_ci| **No.**| **Trace**                      | **Parameter Description**                              | **Process Description**                                          |
94e41f4b71Sopenharmony_ci|:------ | ------------------------------ | -------------------------------------- | ------------------------------------------------ |
95e41f4b71Sopenharmony_ci| 1      | OnIdle, targettime:%" PRId64 " | Timestamp, before which the task is completed.                      | Checks whether there are new events to process in the idle event loop, and if yes, adds the task scheduler to the UI thread and executes the predicted layout task.|
96e41f4b71Sopenharmony_ci| 2      | expiringItem_ count:[%zu]      | Number of lazy-loaded items.                            | Pre-builds items, including processing all lazy-loaded items.                                  |
97e41f4b71Sopenharmony_ci| 3      | List predict                   |                                        | Adds a predicted layout task.                                        |
98e41f4b71Sopenharmony_ci| 4      | Builder:BuildLazyItem [%d]     | Index of the project to be created.                              | Creates an item when needed and caches it.                                   |
99e41f4b71Sopenharmony_ci| 5      | Layout[%s][self:%d][parent:%d] | Tags, which indicate the index of the current node in the UI node tree and the index of the parent node in the UI node tree, respectively.| Lays out the current frame node.                                         |
100e41f4b71Sopenharmony_ci| 6      | Build[%s][self:%d][parent:%d]  | Tags, which indicate the index of the current node in the UI node tree and the index of the parent node in the UI node tree, respectively.| Builds the current frame node.                                         |
101e41f4b71Sopenharmony_ci| 7      | CustomNode:BuildRecycle %s     | JavaScript view name.                                | Triggers re-rendering.                                          |
102e41f4b71Sopenharmony_ci| 8      | ExecuteJS                      |                                        | Runs JavaScript code.                                          |
103e41f4b71Sopenharmony_ci
104e41f4b71Sopenharmony_ci### Page Loading
105e41f4b71Sopenharmony_ci
106e41f4b71Sopenharmony_ciWhen page loading is triggered, the system creates a new page instance and calls the lifecycle functions of the page accordingly. The page layout is loaded in the lifecycle functions, and the data is bound to the page components so that the page can display and update the data.
107e41f4b71Sopenharmony_ci
108e41f4b71Sopenharmony_ciFigure 5 shows the traces for a frame during page loading.
109e41f4b71Sopenharmony_ci
110e41f4b71Sopenharmony_ciFigure 5 Trace lanes for page loading
111e41f4b71Sopenharmony_ci
112e41f4b71Sopenharmony_ci![Trace lanes for page loading](figures/trace-load-frame-rate.png)
113e41f4b71Sopenharmony_ci
114e41f4b71Sopenharmony_ci| **No.**| **Trace**                                                     | **Parameter Description**                              | **Process Description**                      |
115e41f4b71Sopenharmony_ci|:------ | ------------------------------------------------------------- | -------------------------------------- | ---------------------------- |
116e41f4b71Sopenharmony_ci| 1      | PageRouterManager::RunPage                                    |                                        | Preprocesses page routes and loads the page.                |
117e41f4b71Sopenharmony_ci| 2      | PageRouterManager::LoadPage                                   |                                        | Loads the page and processes routes.                     |
118e41f4b71Sopenharmony_ci| 3      | JsiDeclarativeEngine::LoadPageSource                          |                                        | Loads a JavaScript file and parses it into ABC bytecode.|
119e41f4b71Sopenharmony_ci| 4      | JsiDeclarativeEngine::LoadJsWithModule Execute Page code : %s | Page URL.                               | Executes the page code.                      |
120e41f4b71Sopenharmony_ci| 5      | Build[%s][self:%d][parent:%d]                                 | Tags, which indicate the index of the current node in the UI node tree and the index of the parent node in the UI node tree, respectively.| Builds the current frame node.                     |
121e41f4b71Sopenharmony_ci| 6      | CustomNode:BuildItem %s                                       | JavaScript view name.                                | Renders the child node and mounts it to the parent node.            |
122e41f4b71Sopenharmony_ci| 7      | ViewChangeCallback(%d, %d)                                    | Width and height of the view.                               | Called when the view changes.                      |
123e41f4b71Sopenharmony_ci
124e41f4b71Sopenharmony_ci## Practice of Traces
125e41f4b71Sopenharmony_ci
126e41f4b71Sopenharmony_ciThe following example traverses a list in **LazyForEach** mode and uses [Smartperf-Host](../../device-dev/device-test/smartperf-host.md) to trace the code execution process.
127e41f4b71Sopenharmony_ci
128e41f4b71Sopenharmony_ciIn the [sample code](https://gitee.com/openharmony/applications_app_samples/tree/master/code/Performance/PerformanceLibrary/feature/trace), a **\<List>** container component is used to create 120 custom **\<IconView>** components in lazy loading mode. In each **\<IconView>** component, a **\<Flex>** container that holds the **\<Image>** and **\<Text>** components is used to present a list item with text and an image.
129e41f4b71Sopenharmony_ci
130e41f4b71Sopenharmony_ci```ts
131e41f4b71Sopenharmony_ci// src/main/ets/pages/LazyForEachPage.ets
132e41f4b71Sopenharmony_ci
133e41f4b71Sopenharmony_ci@Entry
134e41f4b71Sopenharmony_ci@Component
135e41f4b71Sopenharmony_cistruct LazyForEachPage {
136e41f4b71Sopenharmony_ci  private iconItemSourceList = new ListData();
137e41f4b71Sopenharmony_ci  aboutToAppear() {
138e41f4b71Sopenharmony_ci    // Add data of 120 icon items.
139e41f4b71Sopenharmony_ci     ......
140e41f4b71Sopenharmony_ci  }
141e41f4b71Sopenharmony_ci  build() {
142e41f4b71Sopenharmony_ci    Column() {
143e41f4b71Sopenharmony_ci      Text ('Example of lazy loading')
144e41f4b71Sopenharmony_ci        .fontSize(24)
145e41f4b71Sopenharmony_ci        .fontColor(Color.Black)
146e41f4b71Sopenharmony_ci        .fontWeight(FontWeight.Bold)
147e41f4b71Sopenharmony_ci        .textAlign(TextAlign.Start)
148e41f4b71Sopenharmony_ci        .width('90%')
149e41f4b71Sopenharmony_ci        .height(50)
150e41f4b71Sopenharmony_ci      List({ space: 20 }) {
151e41f4b71Sopenharmony_ci        LazyForEach(this.iconItemSourceList, (item: IconItemModel) => {
152e41f4b71Sopenharmony_ci          ListItem() {
153e41f4b71Sopenharmony_ci            IconItem({ image: item.image, text: item.text })
154e41f4b71Sopenharmony_ci          }
155e41f4b71Sopenharmony_ci        }, (item: IconItemModel, index) => index.toString())
156e41f4b71Sopenharmony_ci      }
157e41f4b71Sopenharmony_ci      .divider({ strokeWidth: 2, startMargin: 20, endMargin: 20 }) // Divider
158e41f4b71Sopenharmony_ci      .width('100%')
159e41f4b71Sopenharmony_ci      .height('100%')
160e41f4b71Sopenharmony_ci      .layoutWeight(1)
161e41f4b71Sopenharmony_ci    }
162e41f4b71Sopenharmony_ci    .width('100%')
163e41f4b71Sopenharmony_ci    .height('100%')
164e41f4b71Sopenharmony_ci    .alignItems(HorizontalAlign.Center)
165e41f4b71Sopenharmony_ci  }
166e41f4b71Sopenharmony_ci}
167e41f4b71Sopenharmony_ci```
168e41f4b71Sopenharmony_ci
169e41f4b71Sopenharmony_ci```ts
170e41f4b71Sopenharmony_ci// src/main/ets/view/IconView.ets
171e41f4b71Sopenharmony_ci
172e41f4b71Sopenharmony_ci@Component
173e41f4b71Sopenharmony_ciexport struct IconItem {
174e41f4b71Sopenharmony_ci  image: string | Resource = '';
175e41f4b71Sopenharmony_ci  text: string | Resource = '';
176e41f4b71Sopenharmony_ci  build() {
177e41f4b71Sopenharmony_ci    Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.Center, alignContent: FlexAlign.Center }) {
178e41f4b71Sopenharmony_ci      Image(this.image)
179e41f4b71Sopenharmony_ci        .height(40)
180e41f4b71Sopenharmony_ci        .width(40)
181e41f4b71Sopenharmony_ci        .objectFit(ImageFit.Contain)
182e41f4b71Sopenharmony_ci        .margin({
183e41f4b71Sopenharmony_ci          left: 15
184e41f4b71Sopenharmony_ci        })
185e41f4b71Sopenharmony_ci      Text(this.text)
186e41f4b71Sopenharmony_ci        .fontSize(20)
187e41f4b71Sopenharmony_ci        .fontColor(Color.Black)
188e41f4b71Sopenharmony_ci        .width(100)
189e41f4b71Sopenharmony_ci        .height(50)
190e41f4b71Sopenharmony_ci        .textAlign(TextAlign.Center)
191e41f4b71Sopenharmony_ci    }
192e41f4b71Sopenharmony_ci    .width('100%')
193e41f4b71Sopenharmony_ci    .height(50)
194e41f4b71Sopenharmony_ci  }
195e41f4b71Sopenharmony_ci}
196e41f4b71Sopenharmony_ci```
197e41f4b71Sopenharmony_ci
198e41f4b71Sopenharmony_ciThe following uses [Smartperf-Host](../../device-dev/device-test/smartperf-host.md) to capture the htrace file and generate a trace lane diagram, helping you better understand the loading process of the sample code. The lane diagram is divided into five parts. Each part is marked with numbers and tags.
199e41f4b71Sopenharmony_ci
200e41f4b71Sopenharmony_ci**Figure 6** Lane diagram of the list traversed in LazyForEach mode
201e41f4b71Sopenharmony_ci
202e41f4b71Sopenharmony_ci![Lane diagram of the list traversed in LazyForEach mode](figures/trace-lazyforeach-channel.png)
203e41f4b71Sopenharmony_ci
204e41f4b71Sopenharmony_ciThe following describes the details of each part.
205e41f4b71Sopenharmony_ci
206e41f4b71Sopenharmony_ci**1. Loading the LazyForEach page**
207e41f4b71Sopenharmony_ci
208e41f4b71Sopenharmony_ci**Figure 7** Lane for loading the LazyForEach page
209e41f4b71Sopenharmony_ci
210e41f4b71Sopenharmony_ci![Lane for loading the LazyForEach page](figures/trace-load-lazyforeach.png)
211e41f4b71Sopenharmony_ci
212e41f4b71Sopenharmony_ci- **H:JsiDeclarativeEngine::LoadPageSource**: loads a JavaScript file and parses it into ABC bytecode.
213e41f4b71Sopenharmony_ci- **H: FlushPipelineWithoutAnimation**: flushes the rendering pipeline.
214e41f4b71Sopenharmony_ci- **H:CustomNode:OnAppear**: builds the current **OnAppear** lifecycle and executes the **aboutToAppear** lifecycle function.
215e41f4b71Sopenharmony_ci- **H:CustomNode:BuildItem LazyForEachPage**: renders the child node and mounts it to the LazyForEachPage page.
216e41f4b71Sopenharmony_ci
217e41f4b71Sopenharmony_ci**2. Laying out and rendering the current frame node Stage, and instructing Render Service to perform rendering**
218e41f4b71Sopenharmony_ci
219e41f4b71Sopenharmony_ci**Figure 8** Lane for Stage layout and rendering
220e41f4b71Sopenharmony_ci
221e41f4b71Sopenharmony_ci![Lane for Stage layout and rendering](figures/trace-stage-frame-rate.png)
222e41f4b71Sopenharmony_ci
223e41f4b71Sopenharmony_ci- **H:Layout[stage][self:1][parent:0]**: lays out the current frame node Stage, which functions as the framework and bears the Page node. Therefore, the tag presentation starts from Stage.
224e41f4b71Sopenharmony_ci  - **H:Measure[%s][self:17][parent:16]**: calculates the layout size of the components **\<Page>**, **\<Column>**, **\<Row>**, **\<Image>**, **\<Text>**, and more.
225e41f4b71Sopenharmony_ci  - **H:Builder:BuildLazyItem [0]** and **H:ListLayoutAlgorithm::MeasureListItem:0**: create a lazy item and calculate the layout size of the list item, respectively.
226e41f4b71Sopenharmony_ci  - **H:Layout[%s][self:38][parent:37]**: lays out the components **\<Page>**, **\<Column>**, **\<Row>**, **\<Image>**, **\<Text>**, and more.
227e41f4b71Sopenharmony_ci- **H:FrameNode::RenderTask**: executes the rendering task.
228e41f4b71Sopenharmony_ci- **H: RequestNextVSync**: requests the Vsync signal of the next frame.
229e41f4b71Sopenharmony_ci
230e41f4b71Sopenharmony_ci**3. Laying out and rendering the current frame node Flex, and instructing Render Service to perform rendering**
231e41f4b71Sopenharmony_ci
232e41f4b71Sopenharmony_ci**Figure 9** Lane for Flex layout and rendering
233e41f4b71Sopenharmony_ci
234e41f4b71Sopenharmony_ci![Lane for Flex layout and rendering](figures/trace-notify-rs.png)
235e41f4b71Sopenharmony_ci
236e41f4b71Sopenharmony_ci- **H:Layout[Flex][self:63][parent:62]**: lays out the current frame node Flex.
237e41f4b71Sopenharmony_ci  - **H:Measure[%s][self:17][parent:16]**: calculates the layout size of the components **\<Image>**, **\<Text>**, and more.
238e41f4b71Sopenharmony_ci- **H:FrameNode::RenderTask**: renders Flex;
239e41f4b71Sopenharmony_ci- **H: RequestNextVSync**: requests the Vsync signal of the next frame.
240e41f4b71Sopenharmony_ci
241e41f4b71Sopenharmony_ci**4. Preprocessing data and adding a predicted layout task**
242e41f4b71Sopenharmony_ci
243e41f4b71Sopenharmony_ci**Figure 10** Lane for preprocessing data and adding a predicted layout task
244e41f4b71Sopenharmony_ci
245e41f4b71Sopenharmony_ci![Lane for preprocessing data and adding a predicted layout task](figures/trace-per-build.png)
246e41f4b71Sopenharmony_ci
247e41f4b71Sopenharmony_ci- **H:Builder:BuildLazyItem [11]**: preprocesses 11 data records.
248e41f4b71Sopenharmony_ci- **H:Layout[ListItem][self:76][parent:-1]**: adds a predicted layout for Flex, **\<Image>**, and **\<Text>**.
249e41f4b71Sopenharmony_ci- **H:FlushMessages**: sends a message to instruct Render Service to perform rendering.
250e41f4b71Sopenharmony_ci
251e41f4b71Sopenharmony_ci**5. Compositing the layers for each node in the render tree**
252e41f4b71Sopenharmony_ci
253e41f4b71Sopenharmony_ci**Figure 11** Lane of compositing the layers for each node in the render tree
254e41f4b71Sopenharmony_ci
255e41f4b71Sopenharmony_ci![Lane for compositing the layer for each node in the render tree](figures/trace-node-tree.png)
256e41f4b71Sopenharmony_ci
257e41f4b71Sopenharmony_ci- **H:AcquireBuffer** and **H:ProcessSurfaceNode:EntryView XYWH[0 0 720 1280]**: obtain the display buffer and draw the EntryView, SystemUi_StatusBar, and SystemUi_NavigationBar.
258e41f4b71Sopenharmony_ci- **H:Repaint**: uses a hardware composer to composite and draw the current node tree.
259e41f4b71Sopenharmony_ci
260e41f4b71Sopenharmony_ci## Custom Traces
261e41f4b71Sopenharmony_ci
262e41f4b71Sopenharmony_ciYou can use hiTraceMeter to customize traces based on service requirements. Currently, ArkTS and native APIs are provided for trace customization. For details, read the following topics:
263e41f4b71Sopenharmony_ci
264e41f4b71Sopenharmony_ci> [Development of Performance Tracing (ArkTS)](../dfx/hitracemeter-guidelines.md)
265e41f4b71Sopenharmony_ci>
266e41f4b71Sopenharmony_ci> [Performance Tracing Development Guide (Native)](../dfx/hitracemeter-native-guidelines.md)
267e41f4b71Sopenharmony_ci
268e41f4b71Sopenharmony_ciAfter custom traces are added, you can view them on [Smartperf-Host](../../device-dev/device-test/smartperf-host.md). They are displayed within an independent lane under the corresponding process.
269e41f4b71Sopenharmony_ci
270e41f4b71Sopenharmony_ciThe figure below shows two lanes that record the duration from the calling of **startTrace** to the calling of **finishTrace**. Two tags (**CUSTOM_TRACE_TAG_1** and **CUSTOM_TRACE_TAG_2**) are used to record the time consumption.
271e41f4b71Sopenharmony_ci
272e41f4b71Sopenharmony_ci**Figure 12** Example of custom traces
273e41f4b71Sopenharmony_ci
274e41f4b71Sopenharmony_ci![Custom trace example](figures/trace-custom-example.png)
275e41f4b71Sopenharmony_ci
276e41f4b71Sopenharmony_ciThe figure below shows two lanes that record the use of **TraceByValue**, which specifies the status value of a trace in the corresponding period. The meanings of the status values can be customized as required. You can move the cursor to the corresponding data block to view the status value. In the figure, the status value of the **CUSTOM_TRACE_TAG_2** tag is 2001 in the period marked in the red box.
277e41f4b71Sopenharmony_ci
278e41f4b71Sopenharmony_ci**Figure 13** Example of a custom status value
279e41f4b71Sopenharmony_ci
280e41f4b71Sopenharmony_ci![Example of a custom status value](figures/trace-custom-value.png)
281e41f4b71Sopenharmony_ci
282e41f4b71Sopenharmony_ci## Working Principles of Traces
283e41f4b71Sopenharmony_ci
284e41f4b71Sopenharmony_ciThe generation of traces depends on the HiTrace component of the DFX subsystem. The hiTraceMeter module provides APIs to trace system performance. For details, read the following topics:
285e41f4b71Sopenharmony_ci
286e41f4b71Sopenharmony_ci> [HiTrace Component](https://gitee.com/openharmony/hiviewdfx_hitrace)
287e41f4b71Sopenharmony_ci>
288e41f4b71Sopenharmony_ci> [hiTraceMeter Module](../reference/apis-performance-analysis-kit/_hitrace.md)
289e41f4b71Sopenharmony_ci
290e41f4b71Sopenharmony_cihiTraceMeter provides two sets of trace start and end APIs to collect statistics on the time consumed by logical behavior. Most time consumption statistics are collected per method. Therefore, hiTraceMeter also provides the macro definitions **HITRACE_METER**, **HITRACE_METER_NAME**, and **HITRACE_METER_FMT** to quickly record the time consumption of a single method. You only need to add them at the beginning of the method. These macro definitions depend on the lifecycle of local variables in the method. The principle is that a trace instance is created at the beginning of the method, and the trace start API is called in the instance constructor. Once the method finishes execution, the trace instance is destructed and the trace end API is called in the instance destructor.
291e41f4b71Sopenharmony_ci
292e41f4b71Sopenharmony_ci### Tracing Example in Applications
293e41f4b71Sopenharmony_ci
294e41f4b71Sopenharmony_ciThe following example shows the use of hiTraceMeter in the ArkUI framework subsystem. The source code comes from the [ArkUI framework](https://gitee.com/openharmony/arkui_ace_engine).
295e41f4b71Sopenharmony_ci
296e41f4b71Sopenharmony_ciThe following code is used to encapsulate the hiTraceMeter APIs. The principle is the same as that of **HITRACE_METER**. Quick tracing is implemented based on the lifecycle of local variables in the method.
297e41f4b71Sopenharmony_ci
298e41f4b71Sopenharmony_ci```cpp
299e41f4b71Sopenharmony_ci// frameworks/base/log/ace_trace.h
300e41f4b71Sopenharmony_ci
301e41f4b71Sopenharmony_ci#define ACE_SCOPED_TRACE(fmt, ...) AceScopedTrace aceScopedTrace(fmt, ##__VA_ARGS__)
302e41f4b71Sopenharmony_ci#define ACE_FUNCTION_TRACE() ACE_SCOPED_TRACE(__func__)
303e41f4b71Sopenharmony_ci
304e41f4b71Sopenharmony_ciclass ACE_FORCE_EXPORT AceScopedTrace final {
305e41f4b71Sopenharmony_cipublic:
306e41f4b71Sopenharmony_ci    explicit AceScopedTrace(const char* format, ...) __attribute__((__format__(printf, 2, 3)));
307e41f4b71Sopenharmony_ci    ~AceScopedTrace();
308e41f4b71Sopenharmony_ci
309e41f4b71Sopenharmony_ci    ACE_DISALLOW_COPY_AND_MOVE(AceScopedTrace);
310e41f4b71Sopenharmony_ci
311e41f4b71Sopenharmony_ciprivate:
312e41f4b71Sopenharmony_ci    bool traceEnabled_ { false };
313e41f4b71Sopenharmony_ci};
314e41f4b71Sopenharmony_ci```
315e41f4b71Sopenharmony_ci
316e41f4b71Sopenharmony_ciThe following code is used to refresh the view synchronization events, including recording frame information, refreshing tasks, drawing and rendering the context, and processing user input. Invoke the macro definition **ACE_FUNCTION_TRACE** at the beginning of the method, record the function name **FlushVsync** as the trace name, and record the function start time. When the function ends, record the function end time to obtain the execution duration.
317e41f4b71Sopenharmony_ci
318e41f4b71Sopenharmony_ci```cpp
319e41f4b71Sopenharmony_ci// frameworks/core/pipeline/pipeline_context.cpp
320e41f4b71Sopenharmony_ci
321e41f4b71Sopenharmony_civoid PipelineContext::FlushVsync(uint64_t nanoTimestamp, uint32_t frameCount)
322e41f4b71Sopenharmony_ci{
323e41f4b71Sopenharmony_ci    ACE_FUNCTION_TRACE();
324e41f4b71Sopenharmony_ci
325e41f4b71Sopenharmony_ci    // Other service logic in the method is omitted here.
326e41f4b71Sopenharmony_ci    // ...
327e41f4b71Sopenharmony_ci}
328e41f4b71Sopenharmony_ci```
329e41f4b71Sopenharmony_ci
330e41f4b71Sopenharmony_ci### Tracing Example on Render Service
331e41f4b71Sopenharmony_ci
332e41f4b71Sopenharmony_ciThe following example shows the use of hiTraceMeter in the graphics subsystem. The source code comes from the [graphics subsystem](https://gitee.com/openharmony/graphic_graphic_2d).
333e41f4b71Sopenharmony_ci
334e41f4b71Sopenharmony_ciThe following code is used to encapsulate the hiTraceMeter APIs.
335e41f4b71Sopenharmony_ci
336e41f4b71Sopenharmony_ci```cpp
337e41f4b71Sopenharmony_ci// utils/log/rs_trace.h
338e41f4b71Sopenharmony_ci
339e41f4b71Sopenharmony_ci#include "hitrace_meter.h"
340e41f4b71Sopenharmony_ci#define ROSEN_TRACE_BEGIN(tag, name) StartTrace(tag, name)
341e41f4b71Sopenharmony_ci#define RS_TRACE_BEGIN(name) ROSEN_TRACE_BEGIN(HITRACE_TAG_GRAPHIC_AGP, name)
342e41f4b71Sopenharmony_ci#define ROSEN_TRACE_END(tag) FinishTrace(tag)
343e41f4b71Sopenharmony_ci#define RS_TRACE_END() ROSEN_TRACE_END(HITRACE_TAG_GRAPHIC_AGP)
344e41f4b71Sopenharmony_ci#define RS_TRACE_NAME(name) HITRACE_METER_NAME(HITRACE_TAG_GRAPHIC_AGP, name)
345e41f4b71Sopenharmony_ci#define RS_TRACE_NAME_FMT(fmt, ...) HITRACE_METER_FMT(HITRACE_TAG_GRAPHIC_AGP, fmt, ##__VA_ARGS__)
346e41f4b71Sopenharmony_ci#define RS_ASYNC_TRACE_BEGIN(name, value) StartAsyncTrace(HITRACE_TAG_GRAPHIC_AGP, name, value)
347e41f4b71Sopenharmony_ci#define RS_ASYNC_TRACE_END(name, value) FinishAsyncTrace(HITRACE_TAG_GRAPHIC_AGP, name, value)
348e41f4b71Sopenharmony_ci#define RS_TRACE_INT(name, value) CountTrace(HITRACE_TAG_GRAPHIC_AGP, name, value)
349e41f4b71Sopenharmony_ci#define RS_TRACE_FUNC() RS_TRACE_NAME(__func__)
350e41f4b71Sopenharmony_ci```
351e41f4b71Sopenharmony_ci
352e41f4b71Sopenharmony_ciThe following code is used to draw images on the display. Invoke the macro definition **RS_TRACE_NAME** at the beginning of the method, combine the function name **ProcessDisplayRenderNode** with a display ID, and record the combination as the trace name. In essence, the macro definition **HITRACE_METER_NAME** for tracing a single method is used. Therefore, you only need to call the **ProcessDisplayRenderNode** function once to collect the function execution start time and end time and obtain the execution duration.
353e41f4b71Sopenharmony_ci
354e41f4b71Sopenharmony_ci```cpp
355e41f4b71Sopenharmony_ci// rosen/modules/render_service/core/pipeline/rs_surface_capture_task.cpp
356e41f4b71Sopenharmony_ci
357e41f4b71Sopenharmony_civoid RSSurfaceCaptureVisitor::ProcessDisplayRenderNode(RSDisplayRenderNode &node)
358e41f4b71Sopenharmony_ci{
359e41f4b71Sopenharmony_ci    RS_TRACE_NAME("RSSurfaceCaptureVisitor::ProcessDisplayRenderNode:" +
360e41f4b71Sopenharmony_ci        std::to_string(node.GetId()));
361e41f4b71Sopenharmony_ci
362e41f4b71Sopenharmony_ci    // Other service logic in the method is omitted here.
363e41f4b71Sopenharmony_ci    // ...
364e41f4b71Sopenharmony_ci}
365e41f4b71Sopenharmony_ci```
366