473,396 Members | 1,966 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

How to get process' CPU usage knowing PID?

18
I'm trying to send out an alert in case when process takes more than certain % of CPU. I'm using the following code to get it:

PerformanceCounter pcProcess = new PerformanceCounter();
pcProcess.CategoryName = "Process";
pcProcess.CounterName = "% Processor Time";
pcProcess.InstanceName = "ProcessName";
pcProcess.NextValue();
System.Threading.Thread.Sleep(1000);
double d = pcProcess.NextValue();
//Console.WriteLine("Process:{0} CPU% {1}", strProcessName, d);

After that I'm using d variable to check if alert needs to be sent out or not.

But the problem is my program is running in many instances meaning all those instances have the same process name in task manager and therefore I don't know which one is which. So the point is I want each instance to check its own % process time, how do I separate them? I can get PID using Process class but how would I use it?
Or maybe you know the way to set a process name in the beginning of the code for each instance?
Also say there are 3 processes with the same name, which one's % Processor Time would PerformanceCounter get using the code above?

Thank you in advance!
Jul 26 '07 #1
17 17888
Dimon
18
please need help ASAP!
Jul 26 '07 #2
Plater
7,872 Expert 4TB
If you are running your .exe 3 times, each will have a different PID.
If they are running as threads, you can use the thread ID.

Other then that I'm not sure what you are asking?
Jul 26 '07 #3
Dimon
18
If you are running your .exe 3 times, each will have a different PID.
If they are running as threads, you can use the thread ID.

Other then that I'm not sure what you are asking?
Yes, that's the whole point - I can get PID for each one but how would I use it to get CPU usage for every instance? Using PerformanceCounter class I can retrieve CPU usage knowing process name, but since process name is the same for all three instances I need to distinguish them somehow so that I know what instance is related to what CPU usage.
Jul 26 '07 #4
Plater
7,872 Expert 4TB
Cannot you get process usage information based on PID? Because I am pretty sure you can get at that from withen the code.
Or you can go through the Process class and maybe find it.
Jul 26 '07 #5
Dimon
18
Cannot you get process usage information based on PID? Because I am pretty sure you can get at that from withen the code.
Or you can go through the Process class and maybe find it.
Well, if I could get this information based on PID I wouldn't post :)
I tried to go through Process class but couldn't find anything except this
Process.GetCurrentProcess().TotalProcessorTime, but I'm not sure how it's related to CPU usage (%) that you can see in task manager.
Jul 26 '07 #6
TRScheel
638 Expert 512MB
Well, if I could get this information based on PID I wouldn't post :)
I tried to go through Process class but couldn't find anything except this
Process.GetCurrentProcess().TotalProcessorTime, but I'm not sure how it's related to CPU usage (%) that you can see in task manager.
Expand|Select|Wrap|Line Numbers
  1. static void Main(string[] args)
  2. {
  3.     foreach (Process p in Process.GetProcesses())
  4.     {
  5.         PerformanceCounter pc = new PerformanceCounter();
  6.         pc.InstanceName = p.ProcessName;
  7.  
  8.         Thread TestThread = new Thread(new ParameterizedThreadStart(GetCPUPercentage));
  9.         TestThread.Start(pc);
  10.     }
  11.     ConsoleUtilities.PressAnyKey("");
  12. }
  13.  
  14. static void GetCPUPercentage(Object pc)
  15. {
  16.     try
  17.     {
  18.         ((PerformanceCounter)pc).CategoryName = "Process";
  19.         ((PerformanceCounter)pc).CounterName = "% Processor Time";
  20.         ((PerformanceCounter)pc).NextValue();
  21.         Thread.Sleep(1000);
  22.         Console.WriteLine("{0}: {1}%", ((PerformanceCounter)pc).InstanceName, ((PerformanceCounter)pc).NextValue());
  23.     }
  24.     catch { }
  25. }
  26.  
That can be easily modified to grab the process in question. For instance, if you passed an array to GetCpuPercentage, and in one item you had the performance counter and in another you had the process, you could grab the PID of the problematic instance.


EDIT: ConsoleUtilities is a library I built of common things I do on the console (such as, say "Press any key to continue")
Jul 26 '07 #7
Dimon
18
Expand|Select|Wrap|Line Numbers
  1. static void Main(string[] args)
  2. {
  3.     foreach (Process p in Process.GetProcesses())
  4.     {
  5.         PerformanceCounter pc = new PerformanceCounter();
  6.         pc.InstanceName = p.ProcessName;
  7.  
  8.         Thread TestThread = new Thread(new ParameterizedThreadStart(GetCPUPercentage));
  9.         TestThread.Start(pc);
  10.     }
  11.     ConsoleUtilities.PressAnyKey("");
  12. }
  13.  
  14. static void GetCPUPercentage(Object pc)
  15. {
  16.     try
  17.     {
  18.         ((PerformanceCounter)pc).CategoryName = "Process";
  19.         ((PerformanceCounter)pc).CounterName = "% Processor Time";
  20.         ((PerformanceCounter)pc).NextValue();
  21.         Thread.Sleep(1000);
  22.         Console.WriteLine("{0}: {1}%", ((PerformanceCounter)pc).InstanceName, ((PerformanceCounter)pc).NextValue());
  23.     }
  24.     catch { }
  25. }
  26.  
That can be easily modified to grab the process in question. For instance, if you passed an array to GetCpuPercentage, and in one item you had the performance counter and in another you had the process, you could grab the PID of the problematic instance.


EDIT: ConsoleUtilities is a library I built of common things I do on the console (such as, say "Press any key to continue")
Thank you.
But I'm not sure how your code helps me. Let's look at the example:
I have program named test.exe. There are three scheduled tasks that runs this program with different parameters on the same server, say "test 1/2/3". If you look at the task manager u'll see 3 processes with the "test" name.
Using your code in main method in loop through the processes it gets process with the "test" name and passes it in to the GetCpuPercentage method, but how does it know what "test" process from the list of processes to grab? There are three of them. I need to write it the way so say instance test1 checks just process that was created by this instance and doesn't touch other two with the same name.

BTW, forgot to mention - I'm working with Framework 1.1 (trying to convince management to switch to at least 2 version), so ParameterizedThreadStart won't really work. I'm not even sure what it's for as I never dealt with such Thread constructor :)
Jul 26 '07 #8
TRScheel
638 Expert 512MB
Thank you.
But I'm not sure how your code helps me. Let's look at the example:
I have program named test.exe. There are three scheduled tasks that runs this program with different parameters on the same server, say "test 1/2/3". If you look at the task manager u'll see 3 processes with the "test" name.
Using your code in main method in loop through the processes it gets process with the "test" name and passes it in to the GetCpuPercentage method, but how does it know what "test" process from the list of processes to grab? There are three of them. I need to write it the way so say instance test1 checks just process that was created by this instance and doesn't touch other two with the same name.

BTW, forgot to mention - I'm working with Framework 1.1 (trying to convince management to switch to at least 2 version), so ParameterizedThreadStart won't really work. I'm not even sure what it's for as I never dealt with such Thread constructor :)

Well, I was getting to the fact that if you pass the process into the thread start function as well, you will have all the information about that specific process (such as the PID, etc).

ParameterizedThreadStart lets you pass variables into a thread start. Without this, you will need to rethink how my method works.

Here is the updated code (and please note, its a staple example of ugly arse code, coded for functionality):

Expand|Select|Wrap|Line Numbers
  1. static void Main(string[] args)
  2. {
  3.     foreach (Process p in Process.GetProcesses())
  4.     {
  5.         PerformanceCounter pc = new PerformanceCounter();
  6.         pc.InstanceName = p.ProcessName;
  7.  
  8.         Thread TestThread = new Thread(new ParameterizedThreadStart(GetCPUPercentage));
  9.         ArrayList al = new ArrayList();
  10.         al.Add(pc);
  11.         al.Add(p);
  12.         TestThread.Start(al);
  13.     }
  14.     ConsoleUtilities.PressAnyKey("");
  15. }
  16.  
  17. static void GetCPUPercentage(Object Params)
  18. {
  19.     PerformanceCounter pc = (PerformanceCounter)((ArrayList)Params)[0];
  20.     Process p = (Process)((ArrayList)Params)[1];
  21.     try
  22.     {
  23.         pc.CategoryName = "Process";
  24.         pc.CounterName = "% Processor Time";
  25.         pc.NextValue();
  26.         Thread.Sleep(1000);
  27.         Console.WriteLine("{0} | {1}: {2}%", pc.InstanceName, p.Id, pc.NextValue());
  28.     }
  29.     catch { }
  30. }
  31.  
Jul 27 '07 #9
Plater
7,872 Expert 4TB
The process class contains a thing that lets you see what the command line arguments to the program was. So if you started the programs:
"test.exe 123"
"test.exe 4-6-7"
"test.exe blah"

You would be able to see the "123", "4-6-7", "blah" in the Process class.
Jul 27 '07 #10
TRScheel
638 Expert 512MB
The process class contains a thing that lets you see what the command line arguments to the program was. So if you started the programs:
"test.exe 123"
"test.exe 4-6-7"
"test.exe blah"

You would be able to see the "123", "4-6-7", "blah" in the Process class.
That underneath the StartInfo properties?
Jul 27 '07 #11
Plater
7,872 Expert 4TB
That underneath the StartInfo properties?
Yup:
Didn't you say each instance of test.exe is monitoring it's own cpu usage?
So couldn't you use Process.GetCurrentProcess(); to get the correct process ID for the running one (as opposed to the PID for one of the other test.exe's running)
Expand|Select|Wrap|Line Numbers
  1. System.Diagnostics.Process p;
  2. p = System.Diagnostics.Process.GetCurrentProcess();
  3. int mypid = p.Id;
  4. string myEXE = p.MainModule.FileName;
  5. string myarguments = p.StartInfo.Arguments;
  6. MessageBox.Show("PID: " + mypid.ToString() + "\r\n" + myEXE + "\r\n" + myarguments); 
  7.  
Jul 27 '07 #12
Dimon
18
Yup:
Didn't you say each instance of test.exe is monitoring it's own cpu usage?
So couldn't you use Process.GetCurrentProcess(); to get the correct process ID for the running one (as opposed to the PID for one of the other test.exe's running)
Expand|Select|Wrap|Line Numbers
  1. System.Diagnostics.Process p;
  2. p = System.Diagnostics.Process.GetCurrentProcess();
  3. int mypid = p.Id;
  4. string myEXE = p.MainModule.FileName;
  5. string myarguments = p.StartInfo.Arguments;
  6. MessageBox.Show("PID: " + mypid.ToString() + "\r\n" + myEXE + "\r\n" + myarguments); 
  7.  
Thank you, but again, I definitely can get PID for each instance, the thing is I don't know how to use it to get CPU usage as PerformanceCounter class uses process name to get it instead of PID.

Note, my program doesn't have parameters, it runs without them, this was just an example. And even if I could get parameter how would it help me to get CPU usage for that particular instance? So the only things I can get are name of the program(process name) and PID for each ones. But I'm not sure how knowing process name helps me since there are 3 of them in task manager with the same name.
So the question is - how would I get CPU usage (%) knowing PID?
Jul 27 '07 #13
Plater
7,872 Expert 4TB
Ok, sorry about that. For some reason I still had it in my head that you wanted the PID.

I just looked into creating the performance counter through windows management console and I saw something under the instances:
"explorer"
"explorer#1"

It appears the first process gets it's name and after that a # and a counter is appended to the isntance name.

So I guess what you would have to do to figure who came first, would be to look at the StartTime of the Process Object....but that seems like it wouldn't be a garuntee.


I think you can compute it from the Process object though.
Like some formula of total time run against the time spent in user/privledged CPU. You might then have to compare that against the system idle process' values of the same thing.
Jul 27 '07 #14
Dimon
18
Ok thank you all, I guess I found the way to do it using Win32_PerfFormattedData_PerfProc_Process class from WMI. It's that simple.
Jul 27 '07 #15
Plater
7,872 Expert 4TB
Ok thank you all, I guess I found the way to do it using Win32_PerfFormattedData_PerfProc_Process class from WMI. It's that simple.
I was gonna suggest WMI at the begining, but I wasn't positive you could find that value in there, and that performance counter thing seemed rather elegant.
Jul 27 '07 #16
Dear all,

I wrote the following application. it does the following things:

1. monitoring CPU usage.
2. if found that it pass the limit (maxCPU) it detect the application which stick the CPU and propose closing / killing it.

Question:
is it possible to tell the PerformanceCounter to monitor the process by its ID and not by its name (for case that I load multiple instances of the same application).

Any other solutions (+ code) will be acceptable.

sorry if my engilsh is not 100%

Netanel.

Expand|Select|Wrap|Line Numbers
  1.     public partial class Form1 : Form
  2.     {
  3.         const int maxCPU = 30;
  4.         PerformanceCounter PCounter;
  5.         PerformanceCounter CCounter;
  6.         System.Diagnostics.Process[] prcs;
  7.         bool monitoring = false;
  8.  
  9.         public Form1()
  10.         {
  11.             InitializeComponent();
  12.             PCounter = new PerformanceCounter();
  13.             CCounter = new PerformanceCounter();
  14.             CCounter.CategoryName = "Processor";
  15.             CCounter.CounterName = "% Processor Time";
  16.             CCounter.InstanceName = "_Total";
  17.         }
  18.         private void MySleep(int dwMS, int dwInterval)
  19.         {
  20.             for (int k = 0; k < dwMS / dwInterval; k++)
  21.             {
  22.                 System.Threading.Thread.Sleep(dwInterval);
  23.                 System.Windows.Forms.Application.DoEvents();
  24.             }
  25.         }
  26.         private void MySleep(int dwMS) { MySleep(dwMS, 100); }
  27.  
  28.         private void button1_Click(object sender, EventArgs e)
  29.         {
  30.             if (monitoring)
  31.                 return;
  32.             monitoring = true;
  33.             while (true)
  34.             {
  35.                 try
  36.                 {
  37.                     System.Diagnostics.Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Normal;
  38.                     while (true)
  39.                     {
  40.                         if (CCounter.NextValue() > maxCPU)
  41.                         {
  42.                             MySleep(1000);
  43.                             if (CCounter.NextValue() > maxCPU)
  44.                                 break;
  45.                         }
  46.                         MySleep(1000);
  47.                     }
  48.                     System.Diagnostics.Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
  49.                     prcs = System.Diagnostics.Process.GetProcesses();
  50.                     PCounter.CategoryName = "Process";
  51.                     PCounter.CounterName = "% Processor Time";
  52.                     for (int i = 0; i < prcs.Length; i++)
  53.                     {
  54.                         if (i % 9 == 0)
  55.                             if (CCounter.NextValue() < maxCPU)
  56.                                 break;
  57.                         if (prcs[i].ProcessName.ToLower().CompareTo("idle")==0)
  58.                             continue;
  59.                         PCounter.InstanceName = prcs[i].ProcessName;
  60.                         PCounter.NextValue();
  61.                         if (PCounter.NextValue() > maxCPU)
  62.                         {
  63.                             System.Threading.Thread.Sleep(1000);
  64.                             if (PCounter.NextValue() > maxCPU)
  65.                                 if (MessageBox.Show("Shutdown " + prcs[i].ProcessName + "?", "CPU", MessageBoxButtons.YesNo) == DialogResult.Yes)
  66.                                 {
  67.                                     try
  68.                                     {
  69.                                         prcs[i].CloseMainWindow();
  70.                                         MySleep(1000);
  71.                                         prcs[i].Close();
  72.                                         MySleep(1000);
  73.                                         prcs[i].Kill();
  74.                                         break;
  75.                                     }
  76.                                     catch { }
  77.                                 }
  78.                         }
  79.  
  80.                     }
  81.  
  82.                 }
  83.                 catch (Exception ex) { MessageBox.Show (ex.Message); }
  84.             }
  85.         }
  86.     }
Jul 30 '07 #17
Dear all,

I got it, code below.

Netanel

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using System.Diagnostics;
  9.  
  10. namespace NDS.IEX.NCC.Process.CPU.Usage
  11. {
  12.     public partial class Form1 : Form
  13.     {
  14.         public String FindInstanceByProcessID(int pid,string name)
  15.         {
  16.             string res;
  17.             int i = 0;
  18.             PerformanceCounter pc = new PerformanceCounter("Process", "ID Process");
  19.             try
  20.             {
  21.                 while (true)
  22.                 {
  23.                     res = name;
  24.                     if (i > 0)
  25.                         res += "#" + i.ToString();
  26.                     i++;
  27.                     pc.InstanceName = res;
  28.                     pc.NextValue();
  29.                     if ((int)pc.NextValue() == pid)
  30.                         return res;
  31.                 }
  32.             }
  33.             catch (Exception ex) { MessageBox.Show(ex.Message); }
  34.             MessageBox.Show ("Not found");
  35.             return "";
  36.         }
  37.  
  38.  
  39.         const int maxCPU = 30;
  40.         const int globalInterval = 750;
  41.         PerformanceCounter PCounter;
  42.         PerformanceCounter CCounter;
  43.         PerformanceCounterCategory cg;
  44.         System.Diagnostics.Process[] prcs;
  45.         bool monitoring = false;
  46.  
  47.         public Form1()
  48.         {
  49.             InitializeComponent();
  50.  
  51.             PCounter = new PerformanceCounter(); //process monitor
  52.             CCounter = new PerformanceCounter(); //cpu monitor
  53.             cg = new PerformanceCounterCategory();
  54.             //PerformanceCounterCategory.Create(
  55.  
  56.             CCounter.CategoryName = "Processor";
  57.             CCounter.CounterName = "% Processor Time";
  58.             CCounter.InstanceName = "_Total";
  59.             PCounter.CategoryName = "Process";
  60.             PCounter.CounterName = "% Processor Time";
  61.         }
  62.         private void MySleep(int dwMS, int dwInterval) //safe sleep
  63.         {
  64.             for (int k = 0; k < dwMS / dwInterval; k++)
  65.             {
  66.                 System.Threading.Thread.Sleep(dwInterval);
  67.                 System.Windows.Forms.Application.DoEvents();
  68.             }
  69.         }
  70.         private void MySleep(int dwMS) { MySleep(dwMS, 100); }
  71.  
  72.         private void btnStartMonitoring_Click(object sender, EventArgs e)
  73.         {
  74.             if (monitoring)
  75.                 return;
  76.             monitoring = true;
  77.             while (true)
  78.             {
  79.                 try
  80.                 {
  81.                     System.Diagnostics.Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Normal;
  82.                     while (true) //monitor the cpu
  83.                     {
  84.                         if (CCounter.NextValue() > maxCPU)
  85.                         {
  86.                             MySleep(globalInterval);
  87.                             if (CCounter.NextValue() > maxCPU)
  88.                                 break;
  89.                         }
  90.                         MySleep(globalInterval);
  91.                     }
  92.                     // find the process that stick the cpu
  93.                     System.Diagnostics.Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
  94.                     prcs = System.Diagnostics.Process.GetProcesses();
  95.                     for (int i = 0; i < prcs.Length; i++)
  96.                     {
  97.                         if (i % 9 == 0)
  98.                             if (CCounter.NextValue() < maxCPU)
  99.                                 break;
  100.                         if (prcs[i].ProcessName.ToLower().CompareTo("idle")==0)
  101.                             continue;
  102.                         PCounter.InstanceName = FindInstanceByProcessID(prcs[i].Id, prcs[i].ProcessName);
  103.                         PCounter.NextValue();
  104.                         if (PCounter.NextValue() > maxCPU)
  105.                         {
  106.                             System.Threading.Thread.Sleep(globalInterval);
  107.                             if (PCounter.NextValue() > maxCPU)
  108.                                 if (MessageBox.Show("Shutdown " + prcs[i].ProcessName + "?", "CPU", MessageBoxButtons.YesNo) == DialogResult.Yes)
  109.                                 {
  110.                                     try
  111.                                     {
  112.                                         prcs[i].CloseMainWindow();
  113.                                         MySleep(globalInterval);
  114.                                         prcs[i].Close();
  115.                                         MySleep(globalInterval);
  116.                                         prcs[i].Kill();
  117.                                     }
  118.                                     catch { }
  119.                                     break;
  120.                                 }
  121.                         }
  122.  
  123.                     }
  124.  
  125.                 }
  126.                 catch (Exception ex) { MessageBox.Show (ex.Message); }
  127.             }
  128.         }
  129.     }
  130. }
  131.  
Jul 30 '07 #18

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: mmf | last post by:
Hi. My problem: How can I make sure that a Python process does not use more that 30% of the CPU at any time. I only want that the process never uses more, but I don't want the process being...
3
by: Dan | last post by:
First, I'm sorry if this question has been asked too many times. I'm new to this news group. The question has to do with the use of popup windows in a web page. I have heard that popup windows...
11
by: Paulo Eduardo | last post by:
Hi, All! We are developing one app for windows 95/98/Me/NT4.0/2000/XP/2003 using Visual C++ 6.0. We need to set the % of CPU Usage to app process. Is there an API to set % of CPU Usage? Can...
4
by: Sefi | last post by:
Good day everyone I'm a bit confused about whether the "Server Application Unavailable" status of my website that frequently occurs when several users are simultaneously logged into it is a symptom...
2
by: John | last post by:
Is the only criteria for worker process recycle 60% physical memory usage?? (I'm on W2K, default setup - I know you can change it in machine.config). Because if so, when using SQL Server on the...
4
by: AN | last post by:
Greetings, We make an ASP.NET web application and we host it for our customers. We have provisioned hardware and hope to be able to service around 200 customers on this hardware. The web...
11
by: Brian Henry | last post by:
Well here is the problem, I have a data set with about 9,000 to 20,000 people in it in the data table "people"... I am then reading it into a list view one at a time row by row... adding each...
35
by: Alex Martelli | last post by:
Having fixed a memory leak (not the leak of a Python reference, some other stuff I wasn't properly freeing in certain cases) in a C-coded extension I maintain, I need a way to test that the leak is...
7
by: Erkan Tatlidil | last post by:
Hi, Our customer has a win2k Xeon 2.0 web server with 2GB of Ram. After a certain time the aspnet_wp.exe consumes %70 of the Ram and comes to a standstill. We end the process and everything is...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.