我试图在C#程序中测量内存使用情况。
我想知道这个Java函数的C#等价物:
ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getCommitted()
表示为堆分配的总内存。我需要这个来知道为我的C#程序分配的内存的总大小。
然后在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到5MB。
看起来:
MyProcess.PrivateMemorySize64; // return ~=25MB
或
MyProcess.WorkingSet64; //return ~=20MB
为正在使用的所有内存提供一个更准确的值。但我不知道该用哪一个。。。
对于全局分配内存,本文建议使用:
Process_MemoryEnd1 = MyProcess.VirtualMemorySize64;
它在整个程序中返回始终相同的值,大约169MB,与Java相比似乎是公平的:从64MB到170MB最大
我仍在寻找一个准确的答案,我发现的都很模糊,我对Windows内存管理不太熟悉,我真的不确定是否能找到我找到的文档:/
这里有一种方法,使用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.");
}
或者使用系统。诊断。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"));
GC
静态类提供所有这类信息。
你可能在GC.GetTotalMemory()
之后。
编辑:
我相信,试图根据当前的根对象来锻炼你的内存足迹。如果您想要为进程分配的总大小(即包括空闲缓冲区),请使用Process
类。例如:
Process.GetCurrentProcess().WorkingSet64;