你想要得到它的即时 CPU 使用率(某种)......
实际上,进程的即时 CPU 使用率并不存在。相反,您必须进行两次测量并计算平均 CPU 使用率,公式非常简单:
AvgCpuUsed = [TotalCPUTime(process,time2) - TotalCPUTime(process,time1)] / [time2-time1]
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;
}
}
}
您应该为您想要监控的每个进程从计时器(或任何您喜欢的间隔方法)调用该类,如果您希望所有进程只需使用Process.GetProcesses 静态方法 p>