How to calculate a private working set (memory)?

How to calculate private working memory set using C #? I'm interested in about the same value as taskmgr.exe .

I use the Process namespace and using methods / data like WorkingSet64 and PrivateMemorySize64 , but these numbers are deleted from time to time by 100 MB or more.

+7
memory-management c # memory
source share
3 answers

This is a very variable number; you cannot calculate it. The Windows memory manager constantly changes pages in and out of RAM. TaskMgr.exe gets it from the performance counter. You can get the same number:

 using System; using System.Diagnostics; class Program { static void Main(string[] args) { string prcName = Process.GetCurrentProcess().ProcessName; var counter = new PerformanceCounter("Process", "Working Set - Private", prcName); Console.WriteLine("{0}K", counter.RawValue / 1024); Console.ReadLine(); } } 

Beware that the number really means a little, it will fall when other processes begin and compete for RAM.

+23
source share

Perhaps GC.GetTotalMemory will provide the necessary data?

0
source share

For future users, here is what I had to do to make sure that the Private Working Set for processes can have multiple instances. I call CurrentMemoryUsage , which gets the corresponding process name from GetNameToUseForMemory . I found this loop slow, even with filtering results where I could. So you see GetNameToUseForMemory with a dictionary to cache the name.

 private static long CurrentMemoryUsage(Process proc) { long currentMemoryUsage; var nameToUseForMemory = GetNameToUseForMemory(proc); using (var procPerfCounter = new PerformanceCounter("Process", "Working Set - Private", nameToUseForMemory)) { //KB is standard currentMemoryUsage = procPerfCounter.RawValue/1024; } return currentMemoryUsage; } private static string GetNameToUseForMemory(Process proc) { if (processId2MemoryProcessName.ContainsKey(proc.Id)) return processId2MemoryProcessName[proc.Id]; var nameToUseForMemory = String.Empty; var category = new PerformanceCounterCategory("Process"); var instanceNames = category.GetInstanceNames().Where(x => x.Contains(proc.ProcessName)); foreach (var instanceName in instanceNames) { using (var performanceCounter = new PerformanceCounter("Process", "ID Process", instanceName, true)) { if (performanceCounter.RawValue != proc.Id) continue; nameToUseForMemory = instanceName; break; } } if(!processId2MemoryProcessName.ContainsKey(proc.Id)) processId2MemoryProcessName.Add(proc.Id, nameToUseForMemory); return nameToUseForMemory; } 
0
source share

All Articles