方法1:
- 某些进程无法正确获取cpu利用率,例如:16位虚拟机:ntvdm,第2种方法可正常获取
public static bool GetCpuUsageByProcessName(string processName, out float cpuUsage)
{
cpuUsage = 0;
try
{
Process[] processes = Process.GetProcessesByName(processName);
if (processes.Length > 0)
{
PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", processes[0].ProcessName);
cpuCounter.NextValue();
System.Threading.Thread.Sleep(1000);
cpuUsage = cpuCounter.NextValue();
}
else
return false;
return true;
}
catch (Exception)
{
return false;
}
}
方法2:
PerformanceCounter curpcp = new PerformanceCounter("Process", "Working Set - Private", cur.ProcessName);
- 使用
public static bool GetCpuUsageByProcessName2(string processName, out float cpuUsage)
{
int times = 0;
START:
cpuUsage = 0;
try
{
Process[] processes = Process.GetProcessesByName(processName);
if (processes.Length > 0)
{
Process cur = processes[0];
PerformanceCounter curpc = new PerformanceCounter("Process", "Working Set", cur.ProcessName);
TimeSpan prevCpuTime = TimeSpan.Zero;
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;
TimeSpan curCpuTime = cur.TotalProcessorTime;
double value = (curCpuTime - prevCpuTime).TotalMilliseconds / interval / Environment.ProcessorCount * 100;
prevCpuTime = curCpuTime;
cpuUsage = (float)value;
Thread.Sleep(interval);
if (cpuUsage > 100)
{
times++;
if (times < 3)
goto START;
else
return false;
}
}
else
return false;
return true;
}
catch (Exception)
{
return false;
}
}
- 类备份
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 Utils
{
public class SystemInfo
{
private int m_ProcessorCount = 0;
private PerformanceCounter pcCpuLoad;
private long m_PhysicalMemory = 0;
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 构造函数
public SystemInfo()
{
pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");
pcCpuLoad.MachineName = ".";
pcCpuLoad.NextValue();
m_ProcessorCount = Environment.ProcessorCount;
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个数
public int ProcessorCount
{
get
{
return m_ProcessorCount;
}
}
#endregion
#region CPU占用率
public float CpuLoad
{
get
{
return pcCpuLoad.NextValue();
}
}
#endregion
#region 可用内存
public long MemoryAvailable
{
get
{
long availablebytes = 0;
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 物理内存
public long PhysicalMemory
{
get
{
return m_PhysicalMemory;
}
}
#endregion
#region 结束指定进程
public static void EndProcess(int pid)
{
try
{
Process process = Process.GetProcessById(pid);
process.Kill();
}
catch { }
}
#endregion
#region 查找所有应用程序标题
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
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
namespace CSharpPerformance
{
class Program
{
static void Main(string[] args)
{
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);
TimeSpan prevCpuTime = TimeSpan.Zero;
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)
{
TimeSpan curCpuTime = cur.TotalProcessorTime;
double value = (curCpuTime - prevCpuTime).TotalMilliseconds / interval / Environment.ProcessorCount * 100;
prevCpuTime = curCpuTime;
Console.WriteLine("{0}:{1} {2:N}KB CPU使用率:{3}", cur.ProcessName, "工作集(进程类)", cur.WorkingSet64 / 1024,value);
Console.WriteLine("{0}:{1} {2:N}KB CPU使用率:{3}", cur.ProcessName, "工作集 ", curpc.NextValue() / 1024,value);
Console.WriteLine("{0}:{1} {2:N}KB CPU使用率:{3}%", cur.ProcessName, "私有工作集 ", curpcp.NextValue() / 1024,curtime.NextValue()/Environment.ProcessorCount);
Console.Write("\r系统CPU使用率:{0}%", totalcpu.NextValue());
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();
}
}
}
C#获取特定进程CPU和内存使用率 - maowang - 博客园 (cnblogs.com)