摘要
本文讲述在DevEco环境中如何在Native C++开发时使用HiTrace,包括代码写法及Trace捕捉。
[toc]
代码写法
在C++中使用HiTrace,需要引入头文件<hitrace/trace.h>, 并在CMakeLists.txt中链接上HiTrace库,如下图所示:
# Others settings
find_library(
# Sets the name of the path variable.
hitrace-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
hitrace_ndk.z
#libhitrace_ndk.z
)
target_link_libraries(nativecode PUBLIC
# Other used libraries
${hitrace-lib}
)
若出现头文件或库文件找不到的情况,则参考此篇博文
Trace捕捉
Trace捕捉有三种方法:
- 通过
hdc shell运行bytrace命令 - 通过DevEco自带的Profiler
- 通过OHOS中自带的SmarPerf App
笔者偏爱方法1,不喜欢用方法2和3,因为这俩操作很麻烦。
bytrace命令的参数选项解释如下,详情参考官方链接
| Option | Description |
|---|---|
| -h, --help | Views the help text for bytrace. |
| -b n, --buffer_size n | Sets the size of the buffer (KB) for storing and reading traces. The default buffer size is 2048 KB. |
| -t n, --time n | Sets the bytrace uptime in seconds, which depends on the time required for analysis. |
| --trace_clock clock | Sets the type of the clock for adding a timestamp to a trace, which can be boot (default), global, mono, uptime, or perf. |
| --trace_begin | Starts capturing traces. |
| --trace_dump | Dumps traces to a specified position (console where you run this command by default). |
| --trace_finish | Stops capturing traces and dumps traces to a specified position (console where you run this command by default). |
| -l, --list_categories | Lists the bytrace categories supported by the device. |
| --overwrite | Sets the action to take when the buffer is full. If this option is used, the latest traces are discarded; if this option is not used, the earliest traces are discarded (default). |
| -o filename, --output filename | Outputs traces to a specified file. |
| -z | Compresses a captured trace |
但是,官方链接里给出trace的命令示例不好使,因为官方示例中把trace导出到了没有写权限的地方(在DAYU200上测得)。所以这里给出一个bytrace命令参考:
bytrace -b <buffer_size> -t <持续时间> --overwrite [<category1>,<category2>,...] > /data/local/tmp/mytrace.ftrace
其中,可用的category可通过如下命令获取:
bytrace --list_categories
我一般常用的命令如下:
# Run in PC terminal
hdc shell "bytrace -b 163840 -t 10 --overwrite ability graphic binder app ace freq idle sched misc multimodalinput ohos sync > /data/local/tmp/mytrace.ftrace";hdc file recv /data/local/tmp/mytrace.ftrace <PATH_ON_PC>
mytrace.ftrace的查看可使用ui.perfetto.dev/