C++ 中的内存分配分析

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/700097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:49:44  来源:igfitidea点击:

Memory Allocation Profiling in C++

c++memory-managementprofiling

提问by amit

I am writing an application and am surprised to see its total memory usage is already too high. I want to profile the dynamic memory usage of my application: How many objects of each kind are there in the heap, and which functions created these objects? Also, how much memory is used by each of the object?

我正在编写一个应用程序,并惊讶地发现它的总内存使用量已经太高了。我想分析我的应用程序的动态内存使用情况:堆中每种类型的对象有多少,哪些函数创建了这些对象?另外,每个对象使用了多少内存?

Is there a simple way to do this? I am working on both linux and windows, so tools of any of the platforms would suffice.

有没有一种简单的方法可以做到这一点?我在 linux 和 windows 上工作,所以任何平台的工具就足够了。

NOTE: I am not concerned with memory leaks here.

注意:我不关心这里的内存泄漏。

回答by javier-sanz

Have you tried Valgrind? It is a profiling tool for Linux. It has a memory checker (for memory leaks and other memory problems) called Memcheck but it has also a heap profiler named Massif.

你试过Valgrind吗?它是 Linux 的分析工具。它有一个名为 Memcheck 的内存检查器(用于内存泄漏和其他内存问题),但它还有一个名为 Massif 的堆分析器。

回答by sth

For simple statistics, just to find out where all the memory is used, you could add a template like this:

对于简单的统计,只是为了找出所有内存的使用位置,您可以添加这样的模板:

template<class T>
class Stats {
  static int instance_count;
public:
  Stats() {
    instance_count++;
  }
  ~Stats() {
    instance_count--;
  }
  static void print() {
    std::cout << instance_count << " instances of " << typeid(T).name() <<
        ", " << sizeof(T) << " bytes each." << std::endl;
  }
};

template<class T>
int Stats<T>::instance_count = 0;

Then you can add this as a base class to the classes you suspect to have a lot of instances, and print out statistics of the current memory usage:

然后你可以把它作为基类添加到你怀疑有很多实例的类中,并打印出当前内存使用情况的统计信息:

class A : Stats<A> {
};

void print_stats() {
  Stats<A>::print();
  Stats<B>::print();
  ...
}

This doesn't show you in which functions the objects were allocated and doesn't give too many details, but it might me enough to locate where memory is wasted.

这并没有显示对象被分配在哪些函数中,也没有提供太多细节,但它可能足以定位内存浪费的位置。

回答by Nitin Bhide

For windows check the functions in "crtdbg.h". crtdbg.h contains the debug version of memory allocation functions. It also contains function for detecting memory leaks, corruptions, checking the validity of heap pointers, etc.

对于 Windows,请检查“crtdbg.h”中的功能。crtdbg.h 包含内存分配函数的调试版本。它还包含用于检测内存泄漏、损坏、检查堆指针有效性等的功能。

I think following functions will be useful for you.

我认为以下功能对您有用。

_CrtMemDumpStatistics _CrtMemDumpAllObjectsSince

_CrtMemDumpStatistics _CrtMemDumpAllObjectsSince

Following MSDN link lists the Heap State Reporting functions and sample code http://msdn.microsoft.com/en-us/library/wc28wkas(VS.80).aspx

以下 MSDN 链接列出了堆状态报告函数和示例代码 http://msdn.microsoft.com/en-us/library/wc28wkas(VS.80).aspx

回答by Canopus

You may try Memory Validator from http://www.softwareverify.com/cpp/memory/index.html

您可以从http://www.softwareverify.com/cpp/memory/index.html尝试内存验证器

It is one of the best tools I have come across for profiling memory usage. 30 days evaluation version is available for free download.

它是我遇到的用于分析内存使用情况的最佳工具之一。30 天评估版可供免费下载。

回答by Charlie Martin

There are several things you can do. The simplest thing is to link a debug malloc library; there are aa number of them available, depending on the details of your environment (eg, google for _malloc_dbg for Windows.)

您可以做几件事。最简单的就是链接一个debug malloc库;有很多可用的,具体取决于您的环境的详细信息(例如,google for _malloc_dbg for Windows。)

The second choice is that you can overload newand deletein C++; it's possible to overload the basic new and delete with new functions that track memory allocation and usage.

第二种选择是你可以在C++中重载newdelete;可以使用跟踪内存分配和使用的新函数来重载基本的 new 和 delete。

回答by mtosic

MTuner- a free C/C++ memory profiler. Description below:

Mtuner- 免费的 C/C++ 内存分析器。说明如下:

MTuner is a multi platform memory profiling, leak detection and analysis tool supporting MSVC, GCC and Clang compilers. Features include: timeline based history of memory activity, powerful filtering, SDK for manual instrumentation with full source code, continuous integration support through command line usage, memory leak detection and much more. Profile any software targetting platforms with GCC or Clang cross compilers. Comes with built in support for Windows, PlayStation 4 and PlayStation 3 platforms and an platform targeted by a Windows based cross compiler.

Mtuner 是一个多平台内存分析、泄漏检测和分析工具,支持 MSVC、GCC 和 Clang 编译器。功能包括:基于时间线的内存活动历史、强大的过滤、用于手动检测的 SDK 和完整的源代码、通过命令行使用的持续集成支持、内存泄漏检测等等。使用 GCC 或 Clang 交叉编译器分析任何面向平台的软件。内置对 Windows、PlayStation 4 和 PlayStation 3 平台的支持,以及一个以基于 Windows 的交叉编译器为目标的平台。

回答by Stewart Lynch

I've just released a win32 native memory profiler MemPro, as a free beta. http://www.puredevsoftware.com/MemPro.htm. It hooks into new/delete and sends data to an external app where you can view the allocations in various different ways. Hope this is of help.

我刚刚发布了一个 win32 本机内存分析器 MemPro,作为免费测试版。http://www.puredevsoftware.com/MemPro.htm。它连接到 new/delete 并将数据发送到外部应用程序,您可以在其中以各种不同的方式查看分配。希望这有帮助。

回答by abyss.7

Try the gperftools- it can:

试试gperftools- 它可以:

  • profile specific parts of code or the whole program at once.
  • represent data via visual directed graphs showing exact function calls and their inheritance.
  • focus on a specific regions of code in a visual graph.
  • show diff between dumps.
  • show allocated space instead of used - all of this is done with the same dump.
  • 一次分析代码的特定部分或整个程序。
  • 通过显示精确函数调用及其继承的可视化有向图来表示数据。
  • 专注于可视化图中的特定代码区域。
  • 显示转储之间的差异。
  • 显示已分配的空间而不是已使用的空间 - 所有这些都是使用相同的转储完成的。

Also, it almost doesn't affect the program efficiency.

而且,它几乎不影响程序效率。

回答by Michael Burr

Chapter 1.10 from Game Programming Gems Volume 2(Amazon link) details a simple but effective Drop-in Debug Memory Manager by Peter Dalton that provides a decent set of statistics when you dump the log.

Game Programming Gems 第 2 卷亚马逊链接)的第 1.10 章详细介绍了 Peter Dalton 的一个简单但有效的嵌入式调试内存管理器,它在您转储日志时提供了一组不错的统计数据。

回答by Ricky Lung

Chapter 4.6 from Game Programming Gems Volume 8(Safari Book preview link) details a advanced memory profiler by Ricky Lung which can show the allocation statistic in a hierarchical call-stack manner and yet support multi-threading.

Game Programming Gems Volume 8(Safari Book 预览链接)的第 4.6 章详细介绍了 Ricky Lung 的高级内存分析器,它可以以分层调用堆栈的方式显示分配统计信息,同时支持多线程。