How to get process' CPU usage knowing PID?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #16
    Originally posted by Dimon
    Ok thank you all, I guess I found the way to do it using Win32_PerfForma ttedData_PerfPr oc_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.

    Comment

    • fischler
      New Member
      • Jul 2007
      • 2

      #17
      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 PerformanceCoun ter 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.

      Code:
          public partial class Form1 : Form
          {
              const int maxCPU = 30;
              PerformanceCounter PCounter;
              PerformanceCounter CCounter;
              System.Diagnostics.Process[] prcs;
              bool monitoring = false;
      
              public Form1()
              {
                  InitializeComponent();
                  PCounter = new PerformanceCounter();
                  CCounter = new PerformanceCounter();
                  CCounter.CategoryName = "Processor";
                  CCounter.CounterName = "% Processor Time";
                  CCounter.InstanceName = "_Total";
              }
              private void MySleep(int dwMS, int dwInterval)
              {
                  for (int k = 0; k < dwMS / dwInterval; k++)
                  {
                      System.Threading.Thread.Sleep(dwInterval);
                      System.Windows.Forms.Application.DoEvents();
                  }
              }
              private void MySleep(int dwMS) { MySleep(dwMS, 100); }
      
              private void button1_Click(object sender, EventArgs e)
              {
                  if (monitoring)
                      return;
                  monitoring = true;
                  while (true)
                  {
                      try
                      {
                          System.Diagnostics.Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Normal;
                          while (true)
                          {
                              if (CCounter.NextValue() > maxCPU)
                              {
                                  MySleep(1000);
                                  if (CCounter.NextValue() > maxCPU)
                                      break;
                              }
                              MySleep(1000);
                          }
                          System.Diagnostics.Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
                          prcs = System.Diagnostics.Process.GetProcesses();
                          PCounter.CategoryName = "Process";
                          PCounter.CounterName = "% Processor Time";
                          for (int i = 0; i < prcs.Length; i++)
                          {
                              if (i % 9 == 0)
                                  if (CCounter.NextValue() < maxCPU)
                                      break;
                              if (prcs[i].ProcessName.ToLower().CompareTo("idle")==0)
                                  continue;
                              PCounter.InstanceName = prcs[i].ProcessName;
                              PCounter.NextValue();
                              if (PCounter.NextValue() > maxCPU)
                              {
                                  System.Threading.Thread.Sleep(1000);
                                  if (PCounter.NextValue() > maxCPU)
                                      if (MessageBox.Show("Shutdown " + prcs[i].ProcessName + "?", "CPU", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                      {
                                          try
                                          {
                                              prcs[i].CloseMainWindow();
                                              MySleep(1000);
                                              prcs[i].Close();
                                              MySleep(1000);
                                              prcs[i].Kill();
                                              break;
                                          }
                                          catch { }
                                      }
                              }
      
                          }
      
                      }
                      catch (Exception ex) { MessageBox.Show (ex.Message); }
                  }
              }
          }

      Comment

      • fischler
        New Member
        • Jul 2007
        • 2

        #18
        Dear all,

        I got it, code below.

        Netanel

        Code:
        using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.Data;
        using System.Drawing;
        using System.Text;
        using System.Windows.Forms;
        using System.Diagnostics;
        
        namespace NDS.IEX.NCC.Process.CPU.Usage
        {
            public partial class Form1 : Form
            {
                public String FindInstanceByProcessID(int pid,string name)
                {
                    string res;
                    int i = 0;
                    PerformanceCounter pc = new PerformanceCounter("Process", "ID Process");
                    try
                    {
                        while (true)
                        {
                            res = name;
                            if (i > 0)
                                res += "#" + i.ToString();
                            i++;
                            pc.InstanceName = res;
                            pc.NextValue();
                            if ((int)pc.NextValue() == pid)
                                return res;
                        }
                    }
                    catch (Exception ex) { MessageBox.Show(ex.Message); }
                    MessageBox.Show ("Not found");
                    return "";
                }
        
        
                const int maxCPU = 30;
                const int globalInterval = 750;
                PerformanceCounter PCounter;
                PerformanceCounter CCounter;
                PerformanceCounterCategory cg;
                System.Diagnostics.Process[] prcs;
                bool monitoring = false;
        
                public Form1()
                {
                    InitializeComponent();
        
                    PCounter = new PerformanceCounter(); //process monitor
                    CCounter = new PerformanceCounter(); //cpu monitor
                    cg = new PerformanceCounterCategory();
                    //PerformanceCounterCategory.Create(
        
                    CCounter.CategoryName = "Processor";
                    CCounter.CounterName = "% Processor Time";
                    CCounter.InstanceName = "_Total";
                    PCounter.CategoryName = "Process";
                    PCounter.CounterName = "% Processor Time";
                }
                private void MySleep(int dwMS, int dwInterval) //safe sleep
                {
                    for (int k = 0; k < dwMS / dwInterval; k++)
                    {
                        System.Threading.Thread.Sleep(dwInterval);
                        System.Windows.Forms.Application.DoEvents();
                    }
                }
                private void MySleep(int dwMS) { MySleep(dwMS, 100); }
        
                private void btnStartMonitoring_Click(object sender, EventArgs e)
                {
                    if (monitoring)
                        return;
                    monitoring = true;
                    while (true)
                    {
                        try
                        {
                            System.Diagnostics.Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Normal;
                            while (true) //monitor the cpu
                            {
                                if (CCounter.NextValue() > maxCPU)
                                {
                                    MySleep(globalInterval);
                                    if (CCounter.NextValue() > maxCPU)
                                        break;
                                }
                                MySleep(globalInterval);
                            }
                            // find the process that stick the cpu
                            System.Diagnostics.Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
                            prcs = System.Diagnostics.Process.GetProcesses();
                            for (int i = 0; i < prcs.Length; i++)
                            {
                                if (i % 9 == 0)
                                    if (CCounter.NextValue() < maxCPU)
                                        break;
                                if (prcs[i].ProcessName.ToLower().CompareTo("idle")==0)
                                    continue;
                                PCounter.InstanceName = FindInstanceByProcessID(prcs[i].Id, prcs[i].ProcessName);
                                PCounter.NextValue();
                                if (PCounter.NextValue() > maxCPU)
                                {
                                    System.Threading.Thread.Sleep(globalInterval);
                                    if (PCounter.NextValue() > maxCPU)
                                        if (MessageBox.Show("Shutdown " + prcs[i].ProcessName + "?", "CPU", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                        {
                                            try
                                            {
                                                prcs[i].CloseMainWindow();
                                                MySleep(globalInterval);
                                                prcs[i].Close();
                                                MySleep(globalInterval);
                                                prcs[i].Kill();
                                            }
                                            catch { }
                                            break;
                                        }
                                }
        
                            }
        
                        }
                        catch (Exception ex) { MessageBox.Show (ex.Message); }
                    }
                }
            }
        }

        Comment

        Working...