[SOLVED] How to get user mode total virtual memory?

Issue

This Content is from Stack Overflow. Question asked by GameRoom

In order to get the memory usage of a process running on Windows in C#, there are several different ways of doing it. You have Process.WorkingSet64, Process.PrivateMemorySize64, Process.VirtualMemorySize64, GC.GetTotalMemory, and probably more. What is private bytes, virtual bytes, working set? and Process Memory Size – Different Counters both explain the differences between these types of memory, but it seems like of these options, none of them are really a great fit for my use case. A lot of people are wanting to do this for the purpose of debugging performance issues, investigating memory leaks, or things like that. So those methods might work for them, but I’m doing something different.

Essentially, I’m trying to measure how much a process is costing me to run. I have a VM that’s hosting this code that costs me $X a month, a specific process is averaging Y% CPU and Z% memory at any given time, and then I’m hoping to use MAX(cpu%, memory%) over time to determine how much it costs for a specific process to be running. The sum of the memory number from various running processes should reach 100 exactly when the VM is out of memory and no new memory can be allocated. The above memory methods seem like a poor fit for this because, as the above answers say, they all include memory that can be shared, that is allocated but not really used, or for some other quirk that makes the measure appropriate for what I want to use it for.

So if those aren’t a good fit, what is?

Follow up question: another aspect of this is finding the total memory available in the operating system. Would How to get user mode total virtual memory? be the right way of doing it for my use case, and using ComputerInfo.TotalVirtualMemory?

Also with CPU I feel a bit more confident that the method I’m using is accurate, that being using Process.TotalProcessorTime, taking the difference at an interval, and dividing it by Environment.ProcessorCount. I’ve seen a lot of references to PerformanceCounter but what I have seems to be about 75% of what the CPU usage looks like in the Task Manager. As per this article I found, https://aaron-margosis.medium.com/task-managers-cpu-numbers-are-all-but-meaningless-2d165b421e43, that is fine since the Task Manager seems to overestimate the true CPU usage of a process. I’m leaving this here just as a confirmation in case anyone wants to point out that that TotalProcessorTime won’t give me accurate info for whatever reason.



Solution

Figured it out.

ComputerInfo myCompInfo = new ComputerInfo();
myCompInfo.TotalVirtualMemory();

BCDEdit does not allow to set virtual address space over 3GB.


This Question was asked in StackOverflow by Alvaromon and Answered by Alvaromon It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?