如何用C#测量内存使用量(我们可以用Java做)?

ala*_*inm 15 c# java memory memory-management

我试图在C#程序中测量内存使用情况.

我想知道这个Java函数的C#等价物:

ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getCommitted()
Run Code Online (Sandbox Code Playgroud)

表示为堆分配的总内存.我需要知道为C#programm分配的内存总大小.

然后在Java中我可以得到用过的内存:

ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed()
Run Code Online (Sandbox Code Playgroud)

目前我在C#中使用它来获取已用内存:

Process_Memory = MyProcess.PrivateMemorySize64;
Run Code Online (Sandbox Code Playgroud)

但我并不完全确定它是等同的.

那么在恢复中如何获得我的C#应用​​程序的总分配空间以及当前在时间t的使用

编辑:

从答案和进一步的研究中我确定了这个:

当前使用的内存

System.GC.GetTotalMemory(false);
Run Code Online (Sandbox Code Playgroud)

给出当前在托管内存中分配的字节数.(http://msdn.microsoft.com/fr-fr/library/system.gc.gettotalmemory.aspx)

该方法返回一个值较低,而我敢肯定它不是真正使用的所有内存的表示,我可以用得到getUsed()Java的.在java中,对于相同的应用程序,使用的内存从5MB开始,最大为125MB.使用C#,我使用上述方法从1到5 MB.

看起来 :

MyProcess.PrivateMemorySize64; // return ~=25MB
Run Code Online (Sandbox Code Playgroud)

要么

MyProcess.WorkingSet64;  //return ~=20MB
Run Code Online (Sandbox Code Playgroud)

为所有正在使用的内存提供更准确的值.但我不知道应该使用哪一个......

对于全局分配的内存, 本文建议使用:

Process_MemoryEnd1 = MyProcess.VirtualMemorySize64;
Run Code Online (Sandbox Code Playgroud)

它在程序中总是返回相同的值,大约169MB,与Java相比似乎是公平的:从64MB到170MB最大

我仍然在寻找一个准确的答案,我发现它非常模糊,而且我对Windows内存管理不是很熟悉,我真的不确定我发现的文档:/

Sea*_*man 15

单向使用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.");         
    }
Run Code Online (Sandbox Code Playgroud)

或者使用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"));
Run Code Online (Sandbox Code Playgroud)


Tys*_*son 9

GC静态类提供了所有这种类型的信息.

你的可能之后GC.GetTotalMemory().

编辑:

我相信,尝试根据当前有根的对象来锻炼你的记忆足迹.如果您想要为进程分配的总大小(即包括空闲缓冲区),请使用Process该类.例如:

Process.GetCurrentProcess().WorkingSet64;
Run Code Online (Sandbox Code Playgroud)