SoFunction
Updated on 2025-03-07

Detailed explanation of C# to obtain CPU and memory usage of specific processes

The first is to obtain a specific process object. You can use the () method to obtain all processes running in the system, or use the () method to obtain the process object corresponding to the current program. When a process object is available, you can create a PerformanceCounter type object through the process object name, and obtain the CPU and memory usage of a specific process by setting the parameters of the PerformanceCounter constructor.

The specific example code is as follows:

First, get all process objects in this machine and output the memory usage of each process at a certain moment:

using System;
using ;
using ;
using ;
using ;
using ;

namespace CSharpPerformance
{//This program can monitor all processes or specified processes' working sets and private working sets in real time  class Program
  {
    static void Main(string[] args)
    {
      // Create a new Stopwatch variable to count program running time      Stopwatch watch = ();
      //Get all process IDs and process names running on the machine, and output the working sets and private working sets used by the Brother process      foreach (Process ps in ())
      {
        PerformanceCounter pf1 = new PerformanceCounter("Process", "Working Set - Private", );
        PerformanceCounter pf2 = new PerformanceCounter("Process", "Working Set", );
        ("{0}:{1} {2:N}KB", , "Work Set(Process class)", ps.WorkingSet64 / 1024);
        ("{0}:{1} {2:N}KB", , "Work Set    ", () / 1024);
        //Private working set        ("{0}:{1} {2:N}KB", , "私有Work Set  ", () / 1024);

      }

      ();
      ();
      ();
    }
  }
}

Among them, the working set ps.WorkingSet64 is static and () is dynamically changed. The working set contains the sum of the exclusive memory of the process when it is running and the memory shared with other processes. The private working set contains only the exclusive memory of the process.

The following set of codes can dynamically display changes in CPU and memory usage of the corresponding processes of this program:

First of all, the class:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;

namespace CSharpPerformance
{
  public class SystemInfo
  {
    private int m_ProcessorCount = 0;  //The number of CPUs    private PerformanceCounter pcCpuLoad;  //CPU Counter    private long m_PhysicalMemory = 0;  //Physical memory
    private const int GW_HWNDFIRST = 0;
    private const int GW_HWNDNEXT = 2;
    private const int GWL_STYLE = (-16);
    private const int WS_VISIBLE = 268435456;
    private const int WS_BORDER = 8388608;

    #region AIP Statement    [DllImport("")]
    extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);

    [DllImport("User32")]
    private extern static int GetWindow(int hWnd, int wCmd);

    [DllImport("User32")]
    private extern static int GetWindowLongA(int hWnd, int wIndx);

    [DllImport("")]
    private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);

    [DllImport("user32", CharSet = )]
    private extern static int GetWindowTextLength(IntPtr hWnd);
    #endregion

    #region constructor    /// <summary>
    /// Constructor, initialization counter, etc.    /// </summary>
    public SystemInfo()
    {
      //Initialize the CPU counter      pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");
       = ".";
      ();

      //The number of CPUs      m_ProcessorCount = ;

      //Get physical memory      ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
      ManagementObjectCollection moc = ();
      foreach (ManagementObject mo in moc)
      {
        if (mo["TotalPhysicalMemory"] != null)
        {
          m_PhysicalMemory = (mo["TotalPhysicalMemory"].ToString());
        }
      }
    }
    #endregion

    #region Number of CPUs    /// <summary>
    /// Get the number of CPUs    /// </summary>
    public int ProcessorCount
    {
      get
      {
        return m_ProcessorCount;
      }
    }
    #endregion

    #region CPU occupancy    /// <summary>
    /// Get CPU occupancy    /// </summary>
    public float CpuLoad
    {
      get
      {
        return ();
      }
    }
    #endregion

    #region Available memory    /// <summary>
    /// Get available memory    /// </summary>
    public long MemoryAvailable
    {
      get
      {
        long availablebytes = 0;
        //ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_PerfRawData_PerfOS_Memory");
        //foreach (ManagementObject mo in ())
        //{
        //  availablebytes = (mo["Availablebytes"].ToString());
        //}
        ManagementClass mos = new ManagementClass("Win32_OperatingSystem");
        foreach (ManagementObject mo in ())
        {
          if (mo["FreePhysicalMemory"] != null)
          {
            availablebytes = 1024 * (mo["FreePhysicalMemory"].ToString());
          }
        }
        return availablebytes;
      }
    }
    #endregion

    #region Physical memory    /// <summary>
    /// Get physical memory    /// </summary>
    public long PhysicalMemory
    {
      get
      {
        return m_PhysicalMemory;
      }
    }
    #endregion

    #region End the specified process    /// <summary>
    /// End the specified process    /// </summary>
    /// <param name="pid">Process ID</param>    public static void EndProcess(int pid)
    {
      try
      {
        Process process = (pid);
        ();
      }
      catch { }
    }
    #endregion


    #region Find all application titles    /// &lt;summary&gt;
    /// Find all application titles    /// &lt;/summary&gt;
    /// <returns>Application title paradigm</returns>    public static List&lt;string&gt; FindAllApps(int Handle)
    {
      List&lt;string&gt; Apps = new List&lt;string&gt;();

      int hwCurr;
      hwCurr = GetWindow(Handle, GW_HWNDFIRST);

      while (hwCurr &gt; 0)
      {
        int IsTask = (WS_VISIBLE | WS_BORDER);
        int lngStyle = GetWindowLongA(hwCurr, GWL_STYLE);
        bool TaskWindow = ((lngStyle &amp; IsTask) == IsTask);
        if (TaskWindow)
        {
          int length = GetWindowTextLength(new IntPtr(hwCurr));
          StringBuilder sb = new StringBuilder(2 * length + 1);
          GetWindowText(hwCurr, sb, );
          string strTitle = ();
          if (!(strTitle))
          {
            (strTitle);
          }
        }
        hwCurr = GetWindow(hwCurr, GW_HWNDNEXT);
      }

      return Apps;
    }
    #endregion   
  }
}

Then execute the code:

using System;
using ;
using ;
using ;
using ;
using ;

namespace CSharpPerformance
{//This program can monitor the working set, private working set and CPU usage rate of the corresponding process of the program itself in real time  class Program
  {
    static void Main(string[] args)
    {
      //Get the current process object      Process cur = ();

      PerformanceCounter curpcp = new PerformanceCounter("Process", "Working Set - Private", );
      PerformanceCounter curpc = new PerformanceCounter("Process", "Working Set", );
      PerformanceCounter curtime = new PerformanceCounter("Process", "% Processor Time", );

      //The last time the CPU was recorded      TimeSpan prevCpuTime = ;
      //Sleep time interval      int interval = 1000;

      PerformanceCounter totalcpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");

      SystemInfo sys = new SystemInfo();
      const int KB_DIV = 1024;
      const int MB_DIV = 1024 * 1024;
      const int GB_DIV = 1024 * 1024 * 1024;
      while (true)
      {
        //The first method calculates CPU usage        //Current time        TimeSpan curCpuTime = ;
        //calculate        double value = (curCpuTime - prevCpuTime).TotalMilliseconds / interval /  * 100;
        prevCpuTime = curCpuTime;

        ("{0}:{1} {2:N}KB CPUUsage rate:{3}", , "Work Set(Process class)", cur.WorkingSet64 / 1024,value);//This working set is only initialized at the beginning and remains unchanged in the later stage        ("{0}:{1} {2:N}KB CPUUsage rate:{3}", , "Work Set    ", () / 1024,value);//This working set is dynamically updated        //The second method of calculating CPU usage        ("{0}:{1} {2:N}KB CPUUsage rate:{3}%", , "私有Work Set  ", () / 1024,()/);
        //(interval);

        //The first method to obtain the system CPU usage        ("\rsystemCPUUsage rate:{0}%", ());
        //(interval);

        //Chapter 2 Method to obtain system CPU and memory usage        ("\rsystemCPUUsage rate:{0}%,system内存使用大小:{1}MB({2}GB)", , ( - ) / MB_DIV, ( - ) / (double)GB_DIV);
        (interval);
      }

      ();
    }
  }
}

The above program can run normally and refresh it once every 1S, so as to dynamically display the CPU and memory usage of the corresponding process of this program.

Original link: /maowang1991/p/

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.