gperftools快速上手

最近在做后处理功能的开发,由于开发有计算效率上的要求,所以学习了一下怎么对程序性能进行分析。这里使用gperftools是因为它能统计部分代码的效率。相比与其他性能分析工具,gperftools有Profiling速度快,灵活性较高的优点。

主流的热点分析工具,分别是GNU gprof、Valgrind和Google perftools,三款工具的主要特点如下表:

工具 使用命令 是否需要重新编译 Profiling速度 是否支持多线程热点分析 是否支持链接库热点分析
GNU gprof ./test; gprof ./test ./gmon.out
Valgrind Valgrind –tool=callgrind ./test 非常慢
Google perftools LD_PRELOAD=/usr/lib/libprofiler.so CPUPROFILE=./test.prof ./test

Ubuntu系统的安装

1
2
3
4
5
6
7
8
9
10
11
12
13
# 克隆代码
git clone https://github.com/gperftools/gperftools.git
# 安装依赖库
sudo apt-get install libunwind8-dev
# 程序编译
cd gperftools
./autogen.sh
./configure
make -j 8
# 安装到系统文件夹
sudo make install
# 刷新动态库文件
ldconfig

.bashrc文件中添加环境变量

gperftools进行时间效率分析

非侵入式

gperftools允许不改变程序分析,用以下命令运行即可

1
LD_PRELOAD=/usr/lib/libprofiler.so.0 CPUPROFILE=./main.prof ./main

LD_PRELOAD:gperftools动态链接库的绝对路径,不同的版本变量名可能不同

CPUPROFILE:输出报告的文件名

侵入式

如果只需要统计部分代码,例如想统计后处理相关代码的性能,可以通过函数来调用gperftools。

1
2
3
4
5
#include <gperftools/profiler.h> //引入相关头文件

ProfilerStart("test.prof"); //分析结束后会生成结果文件test.prof
..... //待分析的代码
ProfilerStop();

编译和链接时需要加-lprofiler选项,运行该段代码会产生名为test.prof的报告

gperftools结果分析

可以以文本形式展示性能报告:

1
google-pprof --text [程序名] [报告文件名]

gperftools支持动态链接库的分析,因此程序名也可以替换成动态链接库名。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Total: 40 samples
6 15.0% 15.0% 6 15.0% __nss_database_lookup
6 15.0% 30.0% 6 15.0% psiginfo
5 12.5% 42.5% 7 17.5% std::__detail::_Executor::_M_dfs
3 7.5% 50.0% 20 50.0% Geometry::generatePlotKeys
2 5.0% 55.0% 5 12.5% Geometry::plotKeyToFSRIDs
2 5.0% 60.0% 37 92.5% PlotKeyExport::getValueByPlotKeys
2 5.0% 65.0% 2 5.0% __cxxabiv1::__si_class_type_info::__do_dyncast
2 5.0% 70.0% 4 10.0% __dynamic_cast
2 5.0% 75.0% 7 17.5% std::__detail::_Executor::_M_rep_once_more
2 5.0% 80.0% 2 5.0% strtoul
1 2.5% 82.5% 21 52.5% Geometry::getPlotKeys[abi:cxx11]
1 2.5% 85.0% 1 2.5% Solver::getFSRFissionRate
1 2.5% 87.5% 1 2.5% __libc_malloc

Total: 40 samples 表示采集到40个样本,默认设置下gperftools采样时间为10 ms。可以通过环境变量CPUPROFILE_FREQUENCY设置采样频率,默认是100次采样。

  • 结果说明,数据每一列意义:
  1. Number of profiling samples in this function 分析样本数量
  2. Percentage of profiling samples in this function 分析样本百分比,也就是该函数在总时间的占比
  3. Percentage of profiling samples in the functions printed so far 累计占比,该函数的时间占比加上之前所有函数的占比
  4. Number of profiling samples in this function and its callees 分析样本数量
  5. Percentage of profiling samples in this function and its callees 分析样本百分比(包含其他函数调用)
  6. Function name 函数名
作者

echo

发布于

2023-04-16

更新于

2024-08-10

许可协议

评论