Using PerformanceCounter class to find the CPU Usage of a given Process

Hi,

Yesterday I was sitting idle and trying to write some dummy windows application. Suddenly I saw that my application is using a lot of CPU resource.

But what if I wanted to know the CPU Usage of an application without using the task manager. Well what if you wanted to show the CPU usage of the current Application to the user. Well I searched a bit and got the answer. So I thought I would share the code with all.

Here is the code for showing the CPU Usage by all the currently running application.
foreach (Process process in Process.GetProcesses())

            {

                using (PerformanceCounter pcProc = new PerformanceCounter("Process", "% Processor Time", process.ProcessName))

                {

                    try

                    {

                        pcProc.NextValue();                       

                        Console.WriteLine("Process:{0} CPU% {1}", process.ProcessName, pcProc.NextValue());

                    }

                    catch { }

                }

            }

To get the CPU Usage of the current process use the following code.

Process p = Process.GetCurrentProcess();

            using (PerformanceCounter pcProcess = new PerformanceCounter("Process", "% Processor Time", p.ProcessName))

            {

                Console.WriteLine("Process:{0} CPU% {1}", p.ProcessName, pcProcess.NextValue());

            }

Vikram

P.S. Don’t forget to import the System.Diagnostics name space.


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Posted on 11/12/2007 5:52:03 AM

Hi,

I'm using .net 2.0 + VSTO 2005.

I tried your code, however each process cpu% = 0 (zero), and this of course not right.

Any suggestions???

Posted on 5/29/2008 7:24:56 AM

for vshost.exe i'm getting cpu usage 100% and for all other apps it is showing 0%, how??

Posted on 5/29/2008 7:47:56 AM

when i try following code:

listBox1.Items.Clear();
Process p = Process.GetCurrentProcess();
using (PerformanceCounter pc = new PerformanceCounter("Process", "% Processor Time", p.ProcessName))
{
listBox1.Items.Add("Process: "+p.ProcessName + pc.NextValue());
}

It show CPU usage 0.

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2008 Vikram Lakhotia