详解C#获取特定进程CPU和内存使用率
首先是获取特定进程对象,可以使用Process.GetProcesses()方法来获取系统中运行的所有进程,或者使用Process.GetCurrentProcess()方法来获取当前程序所对应的进程对象。当有了进程对象后,可以通过进程对象名称来创建PerformanceCounter类型对象,通过设定PerformanceCounter构造函数的参数实现获取特定进程的CPU和内存使用情况。
具体实例代码如下:
首先是获取本机中所有进程对象,分别输出某一时刻各个进程的内存使用情况:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Diagnostics;
usingSystem.Threading;
namespaceCSharpPerformance
{//该程序可以实时监控所有进程或者指定进程的工作集、私有工作集
classProgram
{
staticvoidMain(string[]args)
{
//新建一个Stopwatch变量用来统计程序运行时间
Stopwatchwatch=Stopwatch.StartNew();
//获取本机运行的所有进程ID和进程名,并输出哥进程所使用的工作集和私有工作集
foreach(ProcesspsinProcess.GetProcesses())
{
PerformanceCounterpf1=newPerformanceCounter("Process","WorkingSet-Private",ps.ProcessName);
PerformanceCounterpf2=newPerformanceCounter("Process","WorkingSet",ps.ProcessName);
Console.WriteLine("{0}:{1}{2:N}KB",ps.ProcessName,"工作集(进程类)",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是静态的,pf2.NextValue()是动态变化的,工作集包含进程运行时其独占的内存和与其他进程共享的内存的和,而私有工作集是只包含进程独占的内存。
下面一组代码可以动态显示本程序所对应的进程的CPU和内存使用率的变化:
首先是SystemInfo.cs类:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Diagnostics;
usingSystem.Threading;
usingSystem.IO;
usingSystem.Text;
usingSystem.Management;
usingSystem.Runtime.InteropServices;
namespaceCSharpPerformance
{
publicclassSystemInfo
{
privateintm_ProcessorCount=0;//CPU个数
privatePerformanceCounterpcCpuLoad;//CPU计数器
privatelongm_PhysicalMemory=0;//物理内存
privateconstintGW_HWNDFIRST=0;
privateconstintGW_HWNDNEXT=2;
privateconstintGWL_STYLE=(-16);
privateconstintWS_VISIBLE=268435456;
privateconstintWS_BORDER=8388608;
#regionAIP声明
[DllImport("IpHlpApi.dll")]
externstaticpublicuintGetIfTable(byte[]pIfTable,refuintpdwSize,boolbOrder);
[DllImport("User32")]
privateexternstaticintGetWindow(inthWnd,intwCmd);
[DllImport("User32")]
privateexternstaticintGetWindowLongA(inthWnd,intwIndx);
[DllImport("user32.dll")]
privatestaticexternboolGetWindowText(inthWnd,StringBuildertitle,intmaxBufSize);
[DllImport("user32",CharSet=CharSet.Auto)]
privateexternstaticintGetWindowTextLength(IntPtrhWnd);
#endregion
#region构造函数
///<summary>
///构造函数,初始化计数器等
///</summary>
publicSystemInfo()
{
//初始化CPU计数器
pcCpuLoad=newPerformanceCounter("Processor","%ProcessorTime","_Total");
pcCpuLoad.MachineName=".";
pcCpuLoad.NextValue();
//CPU个数
m_ProcessorCount=Environment.ProcessorCount;
//获得物理内存
ManagementClassmc=newManagementClass("Win32_ComputerSystem");
ManagementObjectCollectionmoc=mc.GetInstances();
foreach(ManagementObjectmoinmoc)
{
if(mo["TotalPhysicalMemory"]!=null)
{
m_PhysicalMemory=long.Parse(mo["TotalPhysicalMemory"].ToString());
}
}
}
#endregion
#regionCPU个数
///<summary>
///获取CPU个数
///</summary>
publicintProcessorCount
{
get
{
returnm_ProcessorCount;
}
}
#endregion
#regionCPU占用率
///<summary>
///获取CPU占用率
///</summary>
publicfloatCpuLoad
{
get
{
returnpcCpuLoad.NextValue();
}
}
#endregion
#region可用内存
///<summary>
///获取可用内存
///</summary>
publiclongMemoryAvailable
{
get
{
longavailablebytes=0;
//ManagementObjectSearchermos=newManagementObjectSearcher("SELECT*FROMWin32_PerfRawData_PerfOS_Memory");
//foreach(ManagementObjectmoinmos.Get())
//{
//availablebytes=long.Parse(mo["Availablebytes"].ToString());
//}
ManagementClassmos=newManagementClass("Win32_OperatingSystem");
foreach(ManagementObjectmoinmos.GetInstances())
{
if(mo["FreePhysicalMemory"]!=null)
{
availablebytes=1024*long.Parse(mo["FreePhysicalMemory"].ToString());
}
}
returnavailablebytes;
}
}
#endregion
#region物理内存
///<summary>
///获取物理内存
///</summary>
publiclongPhysicalMemory
{
get
{
returnm_PhysicalMemory;
}
}
#endregion
#region结束指定进程
///<summary>
///结束指定进程
///</summary>
///<paramname="pid">进程的ProcessID</param>
publicstaticvoidEndProcess(intpid)
{
try
{
Processprocess=Process.GetProcessById(pid);
process.Kill();
}
catch{}
}
#endregion
#region查找所有应用程序标题
///<summary>
///查找所有应用程序标题
///</summary>
///<returns>应用程序标题范型</returns>
publicstaticList<string>FindAllApps(intHandle)
{
List<string>Apps=newList<string>();
inthwCurr;
hwCurr=GetWindow(Handle,GW_HWNDFIRST);
while(hwCurr>0)
{
intIsTask=(WS_VISIBLE|WS_BORDER);
intlngStyle=GetWindowLongA(hwCurr,GWL_STYLE);
boolTaskWindow=((lngStyle&IsTask)==IsTask);
if(TaskWindow)
{
intlength=GetWindowTextLength(newIntPtr(hwCurr));
StringBuildersb=newStringBuilder(2*length+1);
GetWindowText(hwCurr,sb,sb.Capacity);
stringstrTitle=sb.ToString();
if(!string.IsNullOrEmpty(strTitle))
{
Apps.Add(strTitle);
}
}
hwCurr=GetWindow(hwCurr,GW_HWNDNEXT);
}
returnApps;
}
#endregion
}
}
然后是执行代码:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Diagnostics;
usingSystem.Threading;
namespaceCSharpPerformance
{//该程序可以实时监控程序本身对应进程的工作集、私有工作集和CPU使用率
classProgram
{
staticvoidMain(string[]args)
{
//获取当前进程对象
Processcur=Process.GetCurrentProcess();
PerformanceCountercurpcp=newPerformanceCounter("Process","WorkingSet-Private",cur.ProcessName);
PerformanceCountercurpc=newPerformanceCounter("Process","WorkingSet",cur.ProcessName);
PerformanceCountercurtime=newPerformanceCounter("Process","%ProcessorTime",cur.ProcessName);
//上次记录CPU的时间
TimeSpanprevCpuTime=TimeSpan.Zero;
//Sleep的时间间隔
intinterval=1000;
PerformanceCountertotalcpu=newPerformanceCounter("Processor","%ProcessorTime","_Total");
SystemInfosys=newSystemInfo();
constintKB_DIV=1024;
constintMB_DIV=1024*1024;
constintGB_DIV=1024*1024*1024;
while(true)
{
//第一种方法计算CPU使用率
//当前时间
TimeSpancurCpuTime=cur.TotalProcessorTime;
//计算
doublevalue=(curCpuTime-prevCpuTime).TotalMilliseconds/interval/Environment.ProcessorCount*100;
prevCpuTime=curCpuTime;
Console.WriteLine("{0}:{1}{2:N}KBCPU使用率:{3}",cur.ProcessName,"工作集(进程类)",cur.WorkingSet64/1024,value);//这个工作集只是在一开始初始化,后期不变
Console.WriteLine("{0}:{1}{2:N}KBCPU使用率:{3}",cur.ProcessName,"工作集",curpc.NextValue()/1024,value);//这个工作集是动态更新的
//第二种计算CPU使用率的方法
Console.WriteLine("{0}:{1}{2:N}KBCPU使用率:{3}%",cur.ProcessName,"私有工作集",curpcp.NextValue()/1024,curtime.NextValue()/Environment.ProcessorCount);
//Thread.Sleep(interval);
//第一种方法获取系统CPU使用情况
Console.Write("\r系统CPU使用率:{0}%",totalcpu.NextValue());
//Thread.Sleep(interval);
//第二章方法获取系统CPU和内存使用情况
Console.Write("\r系统CPU使用率:{0}%,系统内存使用大小:{1}MB({2}GB)",sys.CpuLoad,(sys.PhysicalMemory-sys.MemoryAvailable)/MB_DIV,(sys.PhysicalMemory-sys.MemoryAvailable)/(double)GB_DIV);
Thread.Sleep(interval);
}
Console.ReadLine();
}
}
}
以上程序可以正常运行,没隔1S刷新一次,实现动态显示本程序对应进程的CPU和内存使用情况。
原文链接:http://www.cnblogs.com/maowang1991/p/3285983.html
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。