跟踪 C++ 内存分配
我正在寻找一种在 C++ 程序中跟踪内存分配的方法.我对内存泄漏不感兴趣,这似乎是大多数工具试图找到的,而是为应用程序创建内存使用配置文件.理想的输出要么是一个大的函数名称列表加上随时间变化的最大分配字节数,要么更好,是随时间推移的堆的图形表示.横轴是时间,纵轴是堆空间.每个函数都会根据分配的堆字节获得自己的颜色并绘制线条.识别分配的对象类型也是加分项.
I am looking for a way to track memory allocations in a C++ program. I am not interested in memory leaks, which seem to be what most tools are trying to find, but rather creating a memory usage profile for the application. Ideal output would be either a big list of function names plus number of maximum allocated bytes over time or better yet, a graphical representation of the heap over time. Horizontal axis is time, vertical axis heap space. Every function would get it's own color and draw lines according to allocated heap bytes. Bonus points for identifying allocated object types as well.
我们的想法是找到内存瓶颈/可视化哪些函数/线程消耗的内存最多,应该作为进一步优化的目标.
The idea is to find memory bottlenecks/to visualize what functions/threads consume the most memory and should be targetted for further optimization.
我曾简要地研究过 Purify、BoundsChecker 和 AQTime,但它们似乎并不是我所追求的.Valgrind 看起来很合适,但是,我使用的是 Windows.Memtrack 看起来很有前景,但需要对源代码进行重大更改.
I have briefly looked at Purify, BoundsChecker and AQTime but they don't seem to be what I'm after. Valgrind looks suitable, however, I'm on Windows. Memtrack looks promising, but requires significant changes to the source code.
我的谷歌技能一定让我失败了,因为这似乎不是一个不常见的要求?应该可以从程序的调试符号和运行时 API 调用中轻松获得创建此类工具所需的所有信息 - 不是吗?
My google skills must have failed me, cause it doesn't seem to be such an uncommon request? All the needed information to create a tool like that should be readily available from the program's debug symbols plus runtime API calls - no?
推荐答案
使用 Valgrind 及其工具 Massif.它的示例输出(其中的一部分):
Use Valgrind and its tool Massif. Its example output (a part of it):
99.48% (20,000B) (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
->49.74% (10,000B) 0x804841A: main (example.c:20)
|
->39.79% (8,000B) 0x80483C2: g (example.c:5)
| ->19.90% (4,000B) 0x80483E2: f (example.c:11)
| | ->19.90% (4,000B) 0x8048431: main (example.c:23)
| |
| ->19.90% (4,000B) 0x8048436: main (example.c:25)
|
->09.95% (2,000B) 0x80483DA: f (example.c:10)
->09.95% (2,000B) 0x8048431: main (example.c:23)
因此,您将获得详细信息:
So, you will get detailed information:
- WHO 分配了内存(上例中的函数:g()、f() 和 main());您还可以获得导致分配功能的完整回溯,
- 内存确实转到了哪个数据结构(上例中没有数据结构),
- 当它发生时,
- 它占所有已分配内存的百分比(g:39.7%,f:9.95%,main:49.7%).
这是Massif 手册
您可以跟踪堆分配和堆栈分配(默认关闭).
You can track heap allocation as well as stack allocation (turned off by default).
附注.我刚刚读到您使用的是 Windows.不过,我会留下答案,因为它给出了您可以从可能的工具中获得什么的图片.
相关文章