Get specific application memory usage

Asked

Viewed 390 times

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 Task Manager value from 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 spent value of memory and CPU of a given application to be the same demonstrated in Task Manager?

3 answers

3

If you want to get the memory of another process, of which you know the PID, you can use GetProcessById:

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

On the other hand, if you know the name of the process, you can use GetProcessesByName. Bear in mind that GetProcessByName returns a array of processes (several different processes can share the same name (e.g Chrome)). That said, you can print the memory of the different processes so:

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

For the values you want to obtain, see here a complete list of properties made available by the object Process.

  • Does this code demonstrate the application’s use of actual memory? I have tested and not shown the demonstrated use in Task Manager

  • This code shows the amount of memory used (and not shared), at the moment, by the process. Note that the value is displayed in bytes and that the value in the task manager is shown in kB, so to get the value in kB you have to divide the value by 1024.

  • I advise you to read this article (in English) on the different types of memory of a process.

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);
  • Gave the following message: Unable to locate Performance Counter with specified category name 'Processor Information', counter name 'Private Bytes''.

2

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

A oneliner would be so:

var tamanhoEmBytes = System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64;
  • I need it for another application independent process with this code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.