我正在尝试在 C# 程序中测量内存使用情况。
我想知道这个 Java 函数的 C# 等价物:
ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getCommitted()
表示为堆分配的总内存。我需要这个来知道为我的 C# 程序分配的内存的总大小。
然后在 Java 中,我可以通过以下方式获取已使用的内存:
ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed()
目前我在 C# 中使用它来获取已用内存:
Process_Memory = MyProcess.PrivateMemorySize64;
但我不完全确定它是等价的。
那么在简历中,我怎样才能获得我的 C# 应用程序的总分配空间和当前的使用情况t?
编辑:
根据答案和进一步的研究,我确定了这一点:
当前正在使用的内存
System.GC.GetTotalMemory(false);
Give the number of bytes currently allocated in managed memory. (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
给出所有正在使用的内存的更准确值。但我不知道我应该使用哪个...
对于全局分配内存 this article建议使用:
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.");
}
或者使用 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"));
关于c# - 如何使用 C# 测量内存使用情况(就像我们在 Java 中所做的那样)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9404946/