如何跟踪重复分配中的生命周期堆使用情况
我有一个程序在其整个生命周期中使用的内存总量比我预期的要多得多,我想看看是否有什么我可以做的。
我使用 Valgrind 的 memcheck 工具来消除内存泄漏,并使用 Valgrind 的 massif 工具查看堆快照。massif 可以告诉我哪些行负责特定时间点的最大堆块。由于 massif 没有显示任何非常大的内容,我怀疑我的问题是多次进行较小分配的特定行。
如果一些数字会有所帮助:程序运行大约 5 秒,进行密集的数值计算。峰值内存使用量为 1MB。终身内存使用量为 10GB。最大的单次分配是 250KB,并进行了 8 次。
因此,我希望看到的不是哪些行在任何特定时间点分配了大量内存,而是在程序的整个生命周期内为每一行分配的总和。我觉得 Valgrind 应该可以访问这些信息,因为它正在跟踪每个分配,但我不知道如何让它告诉我。
任何人都可以建议如何使用 Valgrind 来报告这些信息,或者其他可以做我想做的工具吗?
回答
据我了解,您不想查看当前内存使用情况的“快照”,但您想查看堆栈跟踪完成的累积分配,即使大部分分配的内存已被释放。
为此,您可以尝试使用 --xtree-memory=full 选项。
The xtrees produced by the option --xtree-memory or the xtmemory monitor command are showing the following events/resource consumption describing heap usage:
curB current number of Bytes allocated. The number of allocated bytes is added to the curB value of a stack trace for each allocation. It is decreased when a block allocated by this stack trace is released (by another "freeing" stack trace)
curBk current number of Blocks allocated, maintained similary to curB : +1 for each allocation, -1 when the block is freed.
totB total allocated Bytes. This is increased for each allocation with the number of allocated bytes.
totBk total allocated Blocks, maintained similary to totB : +1 for each allocation.
totFdB total Freed Bytes, increased each time a block is released by this ("freeing") stack trace : + nr freed bytes for each free operation.
totFdBk total Freed Blocks, maintained similarly to totFdB : +1 for each free operation.
Note that the last 4 counts are produced only when the --xtree-memory=full was given at startup.
此选项将与各种工具一起使用,并且可以使用 kcachegrind 将生成的文件可视化。
请参阅https://www.valgrind.org/docs/manual/manual-core.html#opt.xtree-memory
和https://www.valgrind.org/docs/manual/manual-core.html#manual-core .xtree了解更多信息。
您还可以尝试使用 --tool=dhat,这是一种专门用于报告您的程序对分配的内存执行的操作的工具。