valgrind 用法
valgrind 用法
安装
编译安装:
./configure --prefix=/home/fulan/soft/valgrind-3.26.0
make
make install
安装好后添加到 path 环境变量
性能分析
valgrind --tool=callgrind --leak-check=no --track-origins=no ./myprogram
| 参数 | 作用 |
|---|---|
--leak-check=no |
不做泄漏分析(快很多) |
--track-origins=no |
不追踪未初始化来源(非常慢) |
查看结果
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
valgrind --tool=memcheck ./myprogram
设置快捷方式:
alias vcm '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 文件中,而不是输出到标准错误。
有利于后期查看、分析或脚本处理结果。
case 要小而准确,能覆盖测试的流程
处理优先级:
invalid read / invalid write
definitely lost
indirectly lost
possibly lost
still reachable
内存占用
valgrind --tool=massif --stacks=no --time-unit=ms ./bin/skipper
ms_print massif.out.
浙公网安备 33010602011771号