Obtain specific application memory usage

4

I need to get the memory and CPU usage of an application in C #, with the code below (using PerformanceCounter ) did not get the same value as the Task Manager of Windows .

PerformanceCounter cpu;
PerformanceCounter ram;

cpu = new PerformanceCounter("Process", "% Processor Time", "Servidor - estoque", true);
ram = new PerformanceCounter("Process", "Private Bytes", "Servidor - estoque", true);

int Cpu = Convert.ToInt32(cpu.NextValue());
int Ram = Convert.ToInt32(ram.NextValue());


CPU.Value = Cpu;
RAM.Value = (Ram/1024/1024);

How do I make the memory and CPU usage of a given application the same as that shown in Task Manager?

    
asked by anonymous 14.08.2017 / 17:06

3 answers

3

If you want to get the memory of another process that the PID knows about, you can use GetProcessById :

var mem = System.Diagnostics.Process.GetProcessById(1234).PrivateMemorySize64; // valor em bytes

On the other hand, if you know the process name, you can use GetProcessesByName ". Note that GetProcessByName returns an array of processes (many different processes can share the same name (eg Chrome)). With this, you can print the memory of the different processes like this:

foreach(var proc in System.Diagnostics.Process.GetProcessesByName("nome")) 
{
    Console.WriteLine(proc.PrivateMemorySize64);
}

For the values you want to get, see here a complete list of properties provided by object Process .

    
15.08.2017 / 09:10
2

I'm not sure, but I believe you should use "Processor Information" instead of "Process" in the first parameter:

cpu = new PerformanceCounter("Processor Information", "% Processor Time", "Servidor - estoque", true);
ram = new PerformanceCounter("Processor Information", "Private Bytes", "Servidor - estoque", true);
    
14.08.2017 / 17:29
2

For private memory consumption, use the GetCurrentProcess() to reference the current process; the value of the property PrivateMemorySize64 will indicate the size in bytes.

An oneliner would look like this:

var tamanhoEmBytes = System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64;
    
14.08.2017 / 19:36