开发者

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

开发者 https://www.devze.com 2022-12-21 14:18 出处:网络
How 开发者_如何学编程to measure the total memory consumption of the current process programmatically in .NET?Refer to this SO question

How 开发者_如何学编程to measure the total memory consumption of the current process programmatically in .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.


PerformanceCounter class -

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

Here is the CLR memory counter -

http://msdn.microsoft.com/en-us/library/x2tyfybc.aspx


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消