CPU使用率最高的进程的名称

时间:2020-03-05 18:50:00  来源:igfitidea点击:

我有一个Samurize配置,显示类似于任务管理器的CPU使用率图。

如何显示当前CPU使用率最高的进程的名称?

我希望最多每秒更新一次。 Samurize可以调用命令行工具并在屏幕上显示其输出,因此也可以选择。

进一步澄清:

我已经研究过编写自己的命令行c.NET应用程序以枚举从System.Diagnostics.Process.GetProcesses()返回的数组,但是Process实例类似乎未包含CPU百分比属性。

我可以用某种方式计算吗?

解决方案

回答

我们也许可以为此使用Pmon.exe。我们可以将其作为Windows资源工具包工具的一部分来获得(链接指向Server 2003版本,该版本显然也可以在XP中使用)。

回答

Process.TotalProcessorTime

http://msdn.microsoft.com/zh-CN/library/system.diagnostics.process.totalprocessortime.aspx

回答

使用PowerShell:

Get-Process | Sort-Object CPU -desc | Select-Object -first 3 | Format-Table CPU,ProcessName -hidetableheader

返回类似:

16.8641632 System
   12.548072 csrss
  11.9892168 powershell

回答

我们想要获得什么的即时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静态方法,则应从计时器(或者喜欢的间隔方法)中为要监视的每个进程调用该类。