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

Feedback

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 - 2010 Vikram Lakhotia