Detailed C # Get CPU and memory usage for a specific process _c# tutorial

Source: Internet
Author: User
Tags memory usage readline cpu usage

The first is to get a particular process object, either by using the Process.getprocesses () method to get all the processes running on the system, or by using the Process.getcurrentprocess () method to get the process object that the current program corresponds to. When you have a process object, you can create the PerformanceCounter type object by using the process object name to get CPU and memory usage for a particular process by setting the parameter implementation of the PerformanceCounter constructor.

The specific example code is as follows:

The first is to get all the process objects in this machine, outputting the memory usage of each process at a certain moment, respectively:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Diagnostics;

Using System.Threading; 
      namespace Csharpperformance {//This program can monitor all processes in real time or specify the working set of processes, private working Set class program {static void Main (string[] args) {
      Create a new stopwatch variable to count the program run time stopwatch watch = Stopwatch.startnew (); Gets all the process IDs and process names that are running on the machine, and outputs the working set and private working set used by the Columbia process (process PS in process.getprocesses ()) {Performanceco Unter pf1 = new PerformanceCounter ("Process", "Working set-private", Ps.
        ProcessName); PerformanceCounter PF2 = new PerformanceCounter ("Process", "Working Set", Ps.
        ProcessName); Console.WriteLine ("{0}:{1} {2:n}kb", Ps.) ProcessName, "Working set (Process Class)", Ps.
        workingset64/1024); Console.WriteLine ("{0}:{1} {2:n}kb", Ps.) ProcessName, "Working set", PF2.
        NextValue ()/1024); Private Working Set Console.WriteLine ("{0}:{1} {2:n}kb", Ps.) ProcessName, "Private working Set", PF1.

      NextValue ()/1024); } watch.
      Stop ();Console.WriteLine (watch.
      Elapsed);
    Console.ReadLine ();

 }
  }
}

Where the working set PS. WorkingSet64 is static, PF2. NextValue () is dynamic, and the working set contains the memory that the process is running in and the memory it shares with other processes, while the private working set is a memory that contains only the process exclusive.

The following set of code can dynamically display changes in CPU and memory usage for processes that are corresponding to this program:

The first is the SystemInfo.cs class:

Using System;
Using System.Collections.Generic;
Using System.Diagnostics;
Using System.Threading;
Using System.IO;
Using System.Text;
Using System.Management;

Using System.Runtime.InteropServices;  Namespace Csharpperformance {public class SystemInfo {private int m_processorcount = 0;  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 declaration [DllImport ("IpHlpApi.dll")] 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 ("user32.dll")] private static extern boolGetWindowText (int hWnd, StringBuilder title, int maxbufsize);
    [DllImport ("user32", CharSet = CharSet.Auto)] private extern static int getwindowtextlength (INTPTR hWnd); 
    #endregion #region Constructors///<summary>///constructors, initializing counters, etc.///</summary> public systeminfo ()
      {//Initialize CPU counter pccpuload = new PerformanceCounter ("Processor", "% Processor time", "_total");
      Pccpuload.machinename = ".";

      Pccpuload.nextvalue ();

      Number of CPUs m_processorcount = Environment.processorcount;
      Get physical memory ManagementClass MC = new ManagementClass ("Win32_ComputerSystem"); Managementobjectcollection MOC = MC.
      GetInstances (); foreach (ManagementObject mo in MoC) {if (mo["totalphysicalmemory"]!= null) {m_physical Memory = long. Parse (mo["TotalPhysicalMemory").
        ToString ()); #endregion #region CPU number///<summary>///get the number of CPUs///</summary>
    public int ProcessorCount {get {return m_processorcount; }} #endregion #region CPU utilization///<summary>///get CPU Utilization///</summary> public FL
      Oat Cpuload {get {return pccpuload.nextvalue (); }} #endregion #region available memory///<summary>///get available memory///</summary> public long M
        emoryavailable {get {long availablebytes = 0;
        ManagementObjectSearcher mos = new ManagementObjectSearcher ("SELECT * from Win32_PerfRawData_PerfOS_Memory"); foreach (ManagementObject mo in MoS. Get ())//{//availablebytes = long. Parse (mo["Availablebytes").
        ToString ());
        } ManagementClass MoS = new ManagementClass ("Win32_OperatingSystem"); foreach (ManagementObject mo in MoS. GetInstances ()) {if (mo["freephysicalmemory"]!= null) {availablebytes = 1024 * Long. Parse (mo["Freephysicalmemory").
          ToString ());
      } return availablebytes; #endregion #region Physical Memory///<summary>///Get physical memory///</summary> public long P
      Hysicalmemory {get {return m_physicalmemory; #endregion #region End the specified process///<summary>///end the specified process///</summary>///<par Am name= "pid" > Process id</param> public static void endprocess (int pid) {try {P
        Rocess process = Process.getprocessbyid (PID); Process.
      Kill (); #region Find all application headers #endregion the catch {}}///<summary>///Find all application headers///&LT;/SU
    Mmary>///<returns> Application title Paradigm </returns> public static list<string> findallapps (int Handle)

      {list<string> Apps = new list<string> ();
      int Hwcurr; Hwcurr = GetWindow (Handle, Gw_hwndfirst); while (Hwcurr > 0) {int istask = (ws_visible |
        Ws_border);
        int lngstyle = Getwindowlonga (Hwcurr, Gwl_style);
        BOOL Taskwindow = ((Lngstyle & istask) = = Istask);
          if (taskwindow) {int length = Getwindowtextlength (new IntPtr (Hwcurr));
          StringBuilder sb = new StringBuilder (2 * length + 1); GetWindowText (Hwcurr, SB, SB.)
          Capacity); String strtitle = sb.
          ToString (); if (!string.
          IsNullOrEmpty (strtitle)) {Apps.add (strtitle);
      } Hwcurr = GetWindow (Hwcurr, Gw_hwndnext);
    return Apps;

 } #endregion}}

And then the execution code:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Diagnostics;

Using System.Threading;
    namespace Csharpperformance {//The program can monitor the program itself for the working set of the process itself, the private working set and CPU usage class programs {static void Main (string[] args)

      {//Get the current process object processes cur = process.getcurrentprocess (); PerformanceCounter CURPCP = new PerformanceCounter ("Process", "Working set-private", cur.
      ProcessName); PerformanceCounter curpc = new PerformanceCounter ("Process", "Working Set", cur.
      ProcessName); PerformanceCounter curtime = new PerformanceCounter ("Process", "% Processor time", cur.

      ProcessName);
      The last time the CPU was recorded TimeSpan prevcputime = TimeSpan.Zero;

      Sleep 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 = cur.
        Totalprocessortime; Computes the Double value = (curcputime-prevcputime).
        Totalmilliseconds/interval/environment.processorcount * 100;

        Prevcputime = Curcputime; Console.WriteLine (' {0}:{1} {2:N}KB CPU usage: {3} ', cur. ProcessName, Working set (Process Class), cur. Workingset64/1024,value);//This working set is only initialized at the beginning, the later invariant Console.WriteLine ("{0}:{1} {2:N}KB CPU usage: {3}", cur.) ProcessName, "Working set", Curpc. NextValue ()/1024,value);//This working set is dynamically updated the second method of calculating CPU usage Console.WriteLine ("{0}:{1} {2:N}KB CPU usage: {3}%", Cur. ProcessName, "Private working Set", CURPCP. NextValue ()/1024,curtime.
        NextValue ()/environment.processorcount);

        Thread.Sleep (interval); The first method gets the system CPU usage console.write ("\ r system CPU usage: {0}%", totalcpu).
        NextValue ());

        Thread.Sleep (interval); Chapter two methods get system CPU and Memory usage console.write ("\ r system CPU Usage: {0}%, System memory usage size: {1}mB ({2}GB) ", Sys. Cpuload, (sys. Physicalmemory-sys. memoryavailable)/Mb_div, (sys. Physicalmemory-sys.
        memoryavailable)/(double) gb_div);
      Thread.Sleep (interval);
    } console.readline ();

 }
  }
}

The above program can run normally, no 1S refresh once, realize dynamic display of this program corresponding process CPU and memory usage.

Original link: http://www.cnblogs.com/maowang1991/p/3285983.html

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.