你想要得到的是即时CPU使用率(有点)......
实际上,进程的即时CPU 使用率并不存在。相反,您必须进行两次测量并计算平均 CPU 使用率,公式非常简单:
AvgCpuUsed = [TotalCPUTime(进程,时间2) - TotalCPUTime(进程,时间1)] / [时间2-时间1]
Time2 和 Time1 的差异越小,您的测量就越“即时”。 Windows 任务管理器以一秒的间隔计算 CPU 使用率。我发现这已经足够了,您甚至可以考虑以 5 秒为间隔进行测量,因为测量本身会占用 CPU 周期......
所以,首先,获取平均CPU时间
using System.Diagnostics;
float GetAverageCPULoad(int procID, DateTme from, DateTime, to)
{
// For the current process
//Process proc = Process.GetCurrentProcess();
// Or for any other process given its id
Process proc = Process.GetProcessById(procID);
System.TimeSpan lifeInterval = (to - from);
// Get the CPU use
float CPULoad = (proc.TotalProcessorTime.TotalMilliseconds / lifeInterval.TotalMilliseconds) * 100;
// You need to take the number of present cores into account
return CPULoad / System.Environment.ProcessorCount;
}
现在,对于“即时”CPU 负载,您需要一个专门的类:
class ProcLoad
{
// Last time you checked for a process
public Dictionary<int, DateTime> lastCheckedDict = new Dictionary<int, DateTime>();
public float GetCPULoad(int procID)
{
if (lastCheckedDict.ContainsKey(procID))
{
DateTime last = lastCheckedDict[procID];
lastCheckedDict[procID] = DateTime.Now;
return GetAverageCPULoad(procID, last, lastCheckedDict[procID]);
}
else
{
lastCheckedDict.Add(procID, DateTime.Now);
return 0;
}
}
}
您应该从计时器(或您喜欢的任何间隔方法)调用该类您想要监控的每个进程,如果您想要所有进程,只需使用进程.GetProcesses静态方法