简体   繁体   中英

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

如何在.NET中以编程方式测量当前进程的总内存消耗?

Refer to this SO question

Further try this

Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
long totalBytesOfMemoryUsed = currentProcess.WorkingSet64;

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM