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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:36:55  来源:igfitidea点击:

How to measure the total memory consumption of the current process programmatically in .NET?

c#.netperformancememorymemory-management

提问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 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 VirtualMemorySize64with whatever other metric you are interested in. Have a look at the System.Diagnostics.Processtype 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;