C# 如何在 .NET 中以编程方式测量当前进程的总内存消耗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2342023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to measure the total memory consumption of the current process programmatically in .NET?
提问by Jader Dias
How to measure the total memory consumption of the current process programmatically in .NET?
如何在 .NET 中以编程方式测量当前进程的总内存消耗?
采纳答案by HotTester
Refer to this SO question
请参阅此SO 问题
Further try this
进一步尝试这个
Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
long totalBytesOfMemoryUsed = currentProcess.WorkingSet64;
回答by Kris Krause
PerformanceCounter class -
PerformanceCounter 类 -
http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter.aspx
http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter.aspx
There are several of them -
其中有几个——
http://msdn.microsoft.com/en-us/library/w8f5kw2e.aspx
http://msdn.microsoft.com/en-us/library/w8f5kw2e.aspx
Here is the CLR memory counter -
这是 CLR 内存计数器 -
回答by Adam Ralph
If you only want to measure the increase in say, virtual memory usage, caused by some distinct operations you can use the following pattern:-
如果您只想测量由某些不同操作引起的虚拟内存使用量的增加,您可以使用以下模式:-
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var before = System.Diagnostics.Process.GetCurrentProcess().VirtualMemorySize64;
// performs operations here
var after = System.Diagnostics.Process.GetCurrentProcess().VirtualMemorySize64;
This is, of course, assuming that your application in not performing operations on other threads whilst the above operations are running.
当然,这是假设您的应用程序在运行上述操作时不在其他线程上执行操作。
You can replace VirtualMemorySize64
with whatever other metric you are interested in. Have a look at the System.Diagnostics.Process
type to see what is available.
您可以替换VirtualMemorySize64
为您感兴趣的任何其他指标。查看System.Diagnostics.Process
类型以了解可用的内容。
回答by Jader Dias
I have found this very useful:
我发现这非常有用:
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;