詳解C#獲取特定進(jìn)程CPU和內(nèi)存使用率
首先是獲取特定進(jìn)程對(duì)象,可以使用Process.GetProcesses()方法來(lái)獲取系統(tǒng)中運(yùn)行的所有進(jìn)程,或者使用Process.GetCurrentProcess()方法來(lái)獲取當(dāng)前程序所對(duì)應(yīng)的進(jìn)程對(duì)象。當(dāng)有了進(jìn)程對(duì)象后,可以通過(guò)進(jìn)程對(duì)象名稱來(lái)創(chuàng)建PerformanceCounter類型對(duì)象,通過(guò)設(shè)定PerformanceCounter構(gòu)造函數(shù)的參數(shù)實(shí)現(xiàn)獲取特定進(jìn)程的CPU和內(nèi)存使用情況。
具體實(shí)例代碼如下:
首先是獲取本機(jī)中所有進(jìn)程對(duì)象,分別輸出某一時(shí)刻各個(gè)進(jìn)程的內(nèi)存使用情況:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
namespace CSharpPerformance
{//該程序可以實(shí)時(shí)監(jiān)控所有進(jìn)程或者指定進(jìn)程的工作集、私有工作集
class Program
{
static void Main(string[] args)
{
//新建一個(gè)Stopwatch變量用來(lái)統(tǒng)計(jì)程序運(yùn)行時(shí)間
Stopwatch watch = Stopwatch.StartNew();
//獲取本機(jī)運(yùn)行的所有進(jìn)程ID和進(jìn)程名,并輸出哥進(jìn)程所使用的工作集和私有工作集
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, "工作集(進(jìn)程類)", ps.WorkingSet64 / 1024);
Console.WriteLine("{0}:{1} {2:N}KB", ps.ProcessName, "工作集 ", pf2.NextValue() / 1024);
//私有工作集
Console.WriteLine("{0}:{1} {2:N}KB", ps.ProcessName, "私有工作集 ", pf1.NextValue() / 1024);
}
watch.Stop();
Console.WriteLine(watch.Elapsed);
Console.ReadLine();
}
}
}
其中,工作集ps.WorkingSet64是靜態(tài)的,pf2.NextValue()是動(dòng)態(tài)變化的,工作集包含進(jìn)程運(yùn)行時(shí)其獨(dú)占的內(nèi)存和與其他進(jìn)程共享的內(nèi)存的和,而私有工作集是只包含進(jìn)程獨(dú)占的內(nèi)存。
下面一組代碼可以動(dòng)態(tài)顯示本程序所對(duì)應(yīng)的進(jìn)程的CPU和內(nèi)存使用率的變化:
首先是SystemInfo.cs類:
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個(gè)數(shù)
private PerformanceCounter pcCpuLoad; //CPU計(jì)數(shù)器
private long m_PhysicalMemory = 0; //物理內(nèi)存
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聲明
[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 構(gòu)造函數(shù)
/// <summary>
/// 構(gòu)造函數(shù),初始化計(jì)數(shù)器等
/// </summary>
public SystemInfo()
{
//初始化CPU計(jì)數(shù)器
pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");
pcCpuLoad.MachineName = ".";
pcCpuLoad.NextValue();
//CPU個(gè)數(shù)
m_ProcessorCount = Environment.ProcessorCount;
//獲得物理內(nèi)存
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個(gè)數(shù)
/// <summary>
/// 獲取CPU個(gè)數(shù)
/// </summary>
public int ProcessorCount
{
get
{
return m_ProcessorCount;
}
}
#endregion
#region CPU占用率
/// <summary>
/// 獲取CPU占用率
/// </summary>
public float CpuLoad
{
get
{
return pcCpuLoad.NextValue();
}
}
#endregion
#region 可用內(nèi)存
/// <summary>
/// 獲取可用內(nèi)存
/// </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 物理內(nèi)存
/// <summary>
/// 獲取物理內(nèi)存
/// </summary>
public long PhysicalMemory
{
get
{
return m_PhysicalMemory;
}
}
#endregion
#region 結(jié)束指定進(jìn)程
/// <summary>
/// 結(jié)束指定進(jìn)程
/// </summary>
/// <param name="pid">進(jìn)程的 Process ID</param>
public static void EndProcess(int pid)
{
try
{
Process process = Process.GetProcessById(pid);
process.Kill();
}
catch { }
}
#endregion
#region 查找所有應(yīng)用程序標(biāo)題
/// <summary>
/// 查找所有應(yīng)用程序標(biāo)題
/// </summary>
/// <returns>應(yīng)用程序標(biāo)題范型</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
}
}
然后是執(zhí)行代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
namespace CSharpPerformance
{//該程序可以實(shí)時(shí)監(jiān)控程序本身對(duì)應(yīng)進(jìn)程的工作集、私有工作集和CPU使用率
class Program
{
static void Main(string[] args)
{
//獲取當(dāng)前進(jìn)程對(duì)象
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);
//上次記錄CPU的時(shí)間
TimeSpan prevCpuTime = TimeSpan.Zero;
//Sleep的時(shí)間間隔
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)
{
//第一種方法計(jì)算CPU使用率
//當(dāng)前時(shí)間
TimeSpan curCpuTime = cur.TotalProcessorTime;
//計(jì)算
double value = (curCpuTime - prevCpuTime).TotalMilliseconds / interval / Environment.ProcessorCount * 100;
prevCpuTime = curCpuTime;
Console.WriteLine("{0}:{1} {2:N}KB CPU使用率:{3}", cur.ProcessName, "工作集(進(jìn)程類)", cur.WorkingSet64 / 1024,value);//這個(gè)工作集只是在一開始初始化,后期不變
Console.WriteLine("{0}:{1} {2:N}KB CPU使用率:{3}", cur.ProcessName, "工作集 ", curpc.NextValue() / 1024,value);//這個(gè)工作集是動(dòng)態(tài)更新的
//第二種計(jì)算CPU使用率的方法
Console.WriteLine("{0}:{1} {2:N}KB CPU使用率:{3}%", cur.ProcessName, "私有工作集 ", curpcp.NextValue() / 1024,curtime.NextValue()/Environment.ProcessorCount);
//Thread.Sleep(interval);
//第一種方法獲取系統(tǒng)CPU使用情況
Console.Write("\r系統(tǒng)CPU使用率:{0}%", totalcpu.NextValue());
//Thread.Sleep(interval);
//第二章方法獲取系統(tǒng)CPU和內(nèi)存使用情況
Console.Write("\r系統(tǒng)CPU使用率:{0}%,系統(tǒng)內(nèi)存使用大?。簕1}MB({2}GB)", sys.CpuLoad, (sys.PhysicalMemory - sys.MemoryAvailable) / MB_DIV, (sys.PhysicalMemory - sys.MemoryAvailable) / (double)GB_DIV);
Thread.Sleep(interval);
}
Console.ReadLine();
}
}
}
以上程序可以正常運(yùn)行,沒隔1S刷新一次,實(shí)現(xiàn)動(dòng)態(tài)顯示本程序?qū)?yīng)進(jìn)程的CPU和內(nèi)存使用情況。
原文鏈接:http://www.cnblogs.com/maowang1991/p/3285983.html
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#將圖片存放到SQL SERVER數(shù)據(jù)庫(kù)中的方法
這篇文章主要介紹了C#將圖片存放到SQL SERVER數(shù)據(jù)庫(kù)中的方法,以實(shí)例形式較為詳細(xì)的分析了C#保存圖片到SQL Server數(shù)據(jù)庫(kù)的具體步驟與相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-09-09
C#微信開發(fā)之微信公眾號(hào)標(biāo)簽管理功能
這篇文章主要介紹了C#微信開發(fā)之微信公眾號(hào)標(biāo)簽管理功能 的相關(guān)資料,需要的朋友可以參考下2016-05-05
基于c#實(shí)現(xiàn)的九九乘法表(簡(jiǎn)單實(shí)例)
本文主要分享了基于c#實(shí)現(xiàn)的九九乘法表,代碼簡(jiǎn)潔,需要的朋友可以參考下,希望對(duì)大家有所幫助2016-12-12
C#實(shí)現(xiàn)xml文件的讀取與寫入簡(jiǎn)單實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)xml文件的讀取與寫入方法,涉及C#操作XML文件的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-08-08
C#基礎(chǔ)知識(shí)之base關(guān)鍵字介紹
本文主要介紹base關(guān)鍵字的使用方法,base關(guān)鍵字可以調(diào)用基類重寫的方法,可以調(diào)用基類的構(gòu)造方法,還可以在EntityFramework中使用,下面一一介紹。2016-04-04

