【发布时间】:2011-01-21 11:18:45
【问题描述】:
如何在.NET中以编程方式测量当前进程的总内存消耗?
【问题讨论】:
标签: c# .net performance memory memory-management
如何在.NET中以编程方式测量当前进程的总内存消耗?
【问题讨论】:
标签: c# .net performance memory memory-management
PerformanceCounter 类 -
http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter.aspx
有好几个——
http://msdn.microsoft.com/en-us/library/w8f5kw2e.aspx
这里是 CLR 内存计数器 -
【讨论】:
new PerformanceCounter("Process", "Private Bytes", "ConsoleApplication1.vshost").RawValue 看起来很有希望
参考这个SO question
再试试这个
Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
long totalBytesOfMemoryUsed = currentProcess.WorkingSet64;
【讨论】:
如果您只想测量由某些不同操作引起的虚拟内存使用量的增加,您可以使用以下模式:-
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var before = System.Diagnostics.Process.GetCurrentProcess().VirtualMemorySize64;
// performs operations here
var after = System.Diagnostics.Process.GetCurrentProcess().VirtualMemorySize64;
当然,这是假设您的应用程序在上述操作运行时未在其他线程上执行操作。
您可以将VirtualMemorySize64 替换为您感兴趣的任何其他指标。查看System.Diagnostics.Process 类型以了解可用的指标。
【讨论】:
我发现这非常有用:
Thread.MemoryBarrier();
var initialMemory = System.GC.GetTotalMemory(true);
// body
var somethingThatConsumesMemory = Enumerable.Range(0, 100000)
.ToArray();
// end
Thread.MemoryBarrier();
var finalMemory = System.GC.GetTotalMemory(true);
var consumption = finalMemory - initialMemory;
【讨论】: