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

Ash*_*Ash 5 windows performance operating-system

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

如何以当前最高CPU使用率百分比显示进程名称?

我希望每秒最多更新一次.Samurize可以调用命令行工具并在屏幕上显示它的输出,因此这也可以是一个选项.


进一步澄清:

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

我能以某种方式计算出来吗?

Jor*_*oba 6

你想要获得它的即时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;
}
Run Code Online (Sandbox Code Playgroud)

现在,对于"即时"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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果希望所有进程只使用Process.GetProcesses静态方法,则应该为要监视的每个进程从计时器(或任何您喜欢的间隔方法)调用该类.


Pab*_*loG -3

使用 PowerShell:

Get-Process | Sort-Object CPU -desc | Select-Object -first 3 | Format-Table CPU,ProcessName -hidetableheader
Run Code Online (Sandbox Code Playgroud)

返回有点像:

  16.8641632 System
   12.548072 csrss
  11.9892168 powershell
Run Code Online (Sandbox Code Playgroud)

  • 另外,很明显,CPU 并不能告诉你 CPU 的使用百分比。它是进程处于活动状态的总处理器时间(以秒为单位)。powershell "get-process | get-member | Select-Object Name,Definition | sort-object Name | format-list" CPU 定义为 {get=$this.TotalProcessorTime.TotalSeconds;} (9认同)