valgrind 用法

valgrind 用法

安装

下载地址

编译安装:

./configure --prefix=/home/fulan/soft/valgrind-3.26.0
make
make install

安装好后添加到 path 环境变量

内存分析

valgrind --tool=memcheck ./myprogram

性能分析

valgrind --tool=callgrind ./myprogram

查看结果

callgrind_annotate callgrind.out.12345
--auto=yes       # 自动关联源代码
--threshold=1%   # 只显示耗时>1%的函数
--inclusive=yes  # 显示包含子函数的总耗时

对指定代码进行性能分析

valgrind --tool=callgrind --instr-atstart=no ./bin/skipper

在关键代码前后插入:

#include </home/fulan/Empyrean/sandbox/soft/valgrind-3.26.0/include/valgrind/callgrind.h>

CALLGRIND_START_INSTRUMENTATION;
CALLGRIND_ZERO_STATS;

// code

CALLGRIND_STOP_INSTRUMENTATION;

callgrind_annotate --inclusive=yes --threshold=1% callgrind.out.213308

--inclusive=yes

inclusive 的意思是 包含调用树的总开销
函数开销分两类:
Self Cost(自身开销):函数自己执行的指令数
Inclusive Cost(包含调用开销):函数自己 + 它调用的所有子函数开销

--threshold=1%

阈值过滤
意思是:只显示 占总开销 ≥ 1% 的函数

结果可视化

python3 ../../../tools/gprof2dot.py -f callgrind callgrind.out.14947 > out.dot
dot -Tpng out.dot -o out.png

内存分析

valgrind --tool=memcheck --leak-check=full --undef-value-errors=yes --show-possibly-lost=yes --log-file=./mem.log

--leak-check=full
显示 所有 内存泄漏的详细信息,包括:
泄漏的字节数
分配堆栈的调用栈(Backtrace)
是否还可达(reachable)、可能丢失(possibly lost)等状态

--undef-value-errors=yes
启用对“使用未定义值”的检查。
这可以帮助发现未初始化变量的使用或逻辑路径依赖未定义值的问题。

--show-possibly-lost=yes
显示“可能丢失(possibly lost)”的内存块信息。
这是 Valgrind 报告的一种类型,表示它无法确定这块内存是否真的泄漏了,因为它可能仍被程序的一部分间接引用,但找不到引用路径。
启用这个选项有助于定位“潜在”泄漏问题。

--log-file=./mem.log
将 Valgrind 的输出日志写入 ./mem.log 文件中,而不是输出到标准错误。
有利于后期查看、分析或脚本处理结果。
posted @ 2025-12-24 16:48  卑以自牧lq  阅读(6)  评论(0)    收藏  举报