如何用C#测量内存使用量(我们可以用Java做)?
我试图在C#程序中测量内存使用情况。
我想知道这个Java函数的C#等价物:
ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getCommitted()
表示为堆分配的总内存。 我需要知道为C#programm分配的内存总大小。
然后在Java中我可以获得用过的内存:
ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed()
目前我在C#中使用它来获取已用内存:
Process_Memory = MyProcess.PrivateMemorySize64;
但我并不完全确定它是等同的。
那么在简历中如何获得我的C#应用程序的总分配空间以及当前t的当前使用?
编辑:
从答案和进一步研究中我确定了这个:
当前使用的内存
System.GC.GetTotalMemory(false);
给出当前在托管内存中分配的字节数。 ( http://msdn.microsoft.com/fr-fr/library/system.gc.gettotalmemory.aspx )
这个方法返回一个低值,我很确定它并不是所有正在使用的内存的表示,因为我可以使用Java中的 getUsed()
。 在java中,对于相同的应用程序,使用的内存从5MB开始,最大为125MB。 使用C#,我使用上述方法从1到5 MB。
看起来 :
MyProcess.PrivateMemorySize64; // return ~=25MB
要么
MyProcess.WorkingSet64; //return ~=20MB
为所有正在使用的内存提供更准确的值。 但我不知道应该使用哪一个……
对于全局分配的内存, 本文建议使用:
Process_MemoryEnd1 = MyProcess.VirtualMemorySize64;
它在程序中总是返回相同的值 ,大约169MB,与Java相比看起来很公平:从64MB到170MB最大
我仍然在寻找一个准确的答案,我发现它非常含糊,而且我对Windows内存管理不是很熟悉,我真的不确定我发现的文档:/
GC
静态类提供所有这类信息。
您可能在GC.GetTotalMemory()
。
编辑:
我相信,尝试根据当前有根的对象来锻炼你的记忆足迹。 如果您想要为进程分配的总大小(即包括空闲缓冲区),请使用Process
类。 例如:
Process.GetCurrentProcess().WorkingSet64;
只有一种方式,使用GC:
public void Test() { long kbAtExecution = GC.GetTotalMemory(false) / 1024; // do stuff that uses memory here long kbAfter1 = GC.GetTotalMemory(false) / 1024; long kbAfter2 = GC.GetTotalMemory(true) / 1024; Console.WriteLine(kbAtExecution + " Started with this kb."); Console.WriteLine(kbAfter1 + " After the test."); Console.WriteLine(kbAfter1 - kbAtExecution + " Amt. Added."); Console.WriteLine(kbAfter2 + " Amt. After Collection"); Console.WriteLine(kbAfter2 - kbAfter1 + " Amt. Collected by GC."); }
或者使用System.Diagnostics.PerformanceCounter来获取工作集信息:
PerformanceCounter performanceCounter = new PerformanceCounter(); performanceCounter.CategoryName = "Process"; performanceCounter.CounterName = "Working Set"; performanceCounter.InstanceName = Process.GetCurrentProcess().ProcessName; Console.WriteLine(((uint)performanceCounter.NextValue()/1024).ToString("N0"));