如何找出类,对象,变量等消耗的内存

时间:2015-06-13 21:22:35

标签: c# memory-management performance-testing memory-profiling

我正在尝试使用内存分析(这是第一次,所以请原谅我的无知),只是为了看看类,对象,变量,方法等消耗了多少内存。我写了这个示例c#console程序调用MemPlay.exe:

using System;
using System.Text;

namespace MemPlay 
{
   class Program 
   {
      static void Main(string[] args) 
      {
         SomeClass myObject = new SomeClass();

         StringNineMethod();
      }

      private static void StringNineMethod() 
      {         
         string someString0 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

         string someString1 = string.Empty;
         string someString2 = string.Empty;

         for (int i = 0; i < 9999; i++) {
            someString1 += "9";
            someString2 += someString1;
         }
      }
   }   

   class SomeClass 
   {

   }
}

程序运行后,我想找出:

消耗了多少内存
  • MemPlay.exe
  • 计划类
  • SomeClass的
  • 主要方法
  • myObject的
  • StringNineMethod
  • someString0
  • someString1
  • someString2

以及使用了多少处理器:

  • MemPlay.exe
  • 主要方法
  • StringNineMethod

我尝试使用VisualStudio&#39; Performance Diagnostics&#39;工具,但我能看到的是整个函数使用了多少内存(即Main方法,StringNineMethod和String.Concat方法)。

是否有任何方法/工具可以帮助我查看每个变量,对象,类,方法消耗多少内存的所有细节?提前谢谢。

编辑:没有我的问题不是建议的问题重复,因为该问题试图在运行时获取对象大小,我问如何在程序结束后获取此信息。正是Visual Studio的性能诊断工具所做的,它在程序结束执行后提供了这些信息。

2 个答案:

答案 0 :(得分:3)

您可以使用System.Diagnostics命名空间类来获取不同类型的度量和统计信息。要为流程分配总内存,请使用WorkingSet属性(有关MSDN的更多详细信息):

Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
long processAllocatedMemory = currentProcess.WorkingSet64;

这就是过程。

要获得特定的对象分配,您可以使用GC来检查初始内存,然后分配一个对象,最后再次检查内存:

// Check initial memory
var memoryStart = System.GC.GetTotalMemory(true);

// Allocate an object.
var myClass = new SomeClass;

// Check memory after allocation
var memoryEnd = System.GC.GetTotalMemory(true);

要在特定操作后检查特定进程的内存消耗,您可能只能在当前进程上使用与GC相同的技巧(如第一个示例中所示)。

要检查可执行文件和程序,请使用Visual Studio探查器。在VS2013社区版中转到ANALYZE - &gt;性能和诊断菜单(或点击 Alt + F2 )。它允许您分析标准项目,exe,ASP.NET网站和Windows Phone应用程序:

enter image description here

在那里,您选择性能向导,单击开始,然后在下一步中,您可以选择要运行的度量标准。其中一个是内存消耗:

enter image description here

答案 1 :(得分:2)

我用这个: RedGate ANTS

我过去也使用过这个: SciTech Memory Profiler

他们都有免费试用,值得一看。我在不同时期都给我留下了深刻印象,购买了两者的版本。

(我不为两家公司工作 - 只是推荐一些对我有用的东西 - 还有其他工具,例如JetBrains Memory Profiler,但我没有亲自试过,也不能提供意见)。

相关问题