Detailed explanation of C to obtain CPU and memory utilization of specific process
- 2021-11-13 17:58:51
- OfStack
The first is to get a specific process object. You can use the Process. GetProcesses () method to get all the processes running in the system, or use the Process. GetCurrentProcess () method to get the process object corresponding to the current program. When you have a process object, you can create an PerformanceCounter type object by the process object name, and get the CPU and memory usage of a specific process by setting the parameters of the PerformanceCounter constructor.
The specific example code is as follows:
The first is to get all the process objects in this machine and output the memory usage of each process at a certain time:
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 and private working set of the process
class Program
{
static void Main(string[] args)
{
// New 1 A Stopwatch Variables are used to count the running time of programs
Stopwatch watch = Stopwatch.StartNew();
// Gets all processes running locally ID And process name , And output the working set and private working set used by the brother process
foreach (Process ps in Process.GetProcesses())
{
PerformanceCounter 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();
}
}
}
Among them, the working set ps. WorkingSet64 is static, pf2.NextValue () is dynamic, the working set contains the sum of the memory that the process runs and the memory that it shares with other processes, while the private working set only contains the memory that the process only owns.
The following 1 group of code can dynamically display the corresponding process of this program CPU and memory usage changes:
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; //CPU Number
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 bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);
[DllImport("user32", CharSet = CharSet.Auto)]
private extern static int GetWindowTextLength(IntPtr hWnd);
#endregion
#region Constructor
/// <summary>
/// Constructor, initialize counters, and so on
/// </summary>
public SystemInfo()
{
// Initialization CPU Counter
pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");
pcCpuLoad.MachineName = ".";
pcCpuLoad.NextValue();
//CPU Number
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_PhysicalMemory = long.Parse(mo["TotalPhysicalMemory"].ToString());
}
}
}
#endregion
#region CPU Number
/// <summary>
/// Get CPU Number
/// </summary>
public int ProcessorCount
{
get
{
return m_ProcessorCount;
}
}
#endregion
#region CPU Occupation rate
/// <summary>
/// Get CPU Occupation rate
/// </summary>
public float CpuLoad
{
get
{
return pcCpuLoad.NextValue();
}
}
#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 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 PhysicalMemory
{
get
{
return m_PhysicalMemory;
}
}
#endregion
#region End the specified process
/// <summary>
/// End the specified process
/// </summary>
/// <param name="pid"> Processed Process ID</param>
public static void EndProcess(int pid)
{
try
{
Process process = Process.GetProcessById(pid);
process.Kill();
}
catch { }
}
#endregion
#region Find all application titles
/// <summary>
/// Find all application titles
/// </summary>
/// <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
}
}
Then there is 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 working set, private working set and the corresponding process of the program in real time CPU Utilization rate
class Program
{
static void Main(string[] args)
{
// Gets the current process object
Process 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);
// Last Record CPU Time of
TimeSpan prevCpuTime = TimeSpan.Zero;
//Sleep Time interval of
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)
{
// No. 1 1 Calculate by different methods CPU Utilization rate
// Current time
TimeSpan curCpuTime = cur.TotalProcessorTime;
// Calculation
double value = (curCpuTime - prevCpuTime).TotalMilliseconds / interval / Environment.ProcessorCount * 100;
prevCpuTime = curCpuTime;
Console.WriteLine("{0}:{1} {2:N}KB CPU Utilization rate: {3}", cur.ProcessName, " Working set ( Process class )", cur.WorkingSet64 / 1024,value);// This working set is only available in the 1 Initialization starts, but does not change later
Console.WriteLine("{0}:{1} {2:N}KB CPU Utilization rate: {3}", cur.ProcessName, " Working set ", curpc.NextValue() / 1024,value);// This working set is dynamically updated
// No. 1 2 Species calculation CPU Utilization method
Console.WriteLine("{0}:{1} {2:N}KB CPU Utilization rate: {3}%", cur.ProcessName, " Private working set ", curpcp.NextValue() / 1024,curtime.NextValue()/Environment.ProcessorCount);
//Thread.Sleep(interval);
// No. 1 1 A method to obtain the system CPU Usage
Console.Write("\r System CPU Utilization rate: {0}%", totalcpu.NextValue());
//Thread.Sleep(interval);
// No. 1 2 Chapter method acquisition system CPU And memory usage
Console.Write("\r System CPU Utilization rate: {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, not every 1S refresh once, to achieve dynamic display of the program corresponding to the process of CPU and memory usage.
Original link: http://www.cnblogs.com/maowang1991/p/3285983. html