あなたが取得したいのは、その瞬間のCPU使用率(種類)です...
実際には、プロセスの瞬間的な CPU 使用率は存在しません。代わりに、2 つの測定を行い、平均 CPU 使用率を計算する必要があります。式は非常に単純です。
AvgCpuUsed = [TotalCPUTime(プロセス、時間 2) - TotalCPUTime(プロセス、時間 1)] / [時間 2 - 時間 1]
Time2 と Time1 の差が小さいほど、測定はより「即時」になります。Windows タスク マネージャーは、1 秒間隔で 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静的メソッドを使用するだけの場合は、監視するプロセスごとにタイマー (または任意の間隔メソッド) からそのクラスを呼び出す必要があります。