我有一个 萨穆里泽 配置显示类似于任务管理器的 CPU 使用率图表。

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

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


进一步澄清:

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

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

有帮助吗?

解决方案

使用 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(进程,时间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 静态方法

以 Frederic 的答案为基础并利用页面底部的代码 这里 (有关用法的示例,请参见 post)加入全套流程 Get-Process, ,我们得到以下结果:

$sampleInterval = 3

$process1 = Get-Process |select Name,Id, @{Name="Sample1CPU"; Expression = {$_.CPU}}

Start-Sleep -Seconds $sampleInterval

$process2 = Get-Process | select Id, @{Name="Sample2CPU"; Expression = {$_.CPU}}

$samples = Join-Object -Left $process1 -Right $process2 -LeftProperties Name,Sample1CPU -RightProperties Sample2CPU -Where {$args[0].Id -eq $args[1].Id}

$samples | select Name,@{Name="CPU Usage";Expression = {($_.Sample2CPU-$_.Sample1CPU)/$sampleInterval * 100}} | sort -Property "CPU Usage" -Descending | select -First 10 | ft -AutoSize

其中给出了一个示例输出

Name                  CPU Usage
----                  ---------
firefox        20.8333333333333
powershell_ise 5.72916666666667
Battle.net               1.5625
Skype                    1.5625
chrome                   1.5625
chrome         1.04166666666667
chrome         1.04166666666667
chrome         1.04166666666667
chrome         1.04166666666667
LCore          1.04166666666667

你也许可以使用 执行程序 为了这。您可以将其作为 Windows 资源工具包工具 (链接是Server 2003版本,显然也可以在XP中使用)。

不知何故

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

无法从远程计算机获取 CPU 信息。我必须想出这个。

Get-Counter '\Process(*)\% Processor Time' | Select-Object -ExpandProperty countersamples | Select-Object -Property instancename, cookedvalue| Sort-Object -Property cookedvalue -Descending| Select-Object -First 10| ft -AutoSize

谢谢你的公式,豪尔赫。我不太明白为什么必须除以核心数量,但我得到的数字与任务管理器相匹配。这是我的 powershell 代码:

$procID = 4321

$time1 = Get-Date
$cpuTime1 = Get-Process -Id $procID | Select -Property CPU

Start-Sleep -s 2

$time2 = Get-Date
$cpuTime2 = Get-Process -Id $procID | Select -Property CPU

$avgCPUUtil = ($cpuTime2.CPU - $cpuTime1.CPU)/($time2-$time1).TotalSeconds *100 / [System.Environment]::ProcessorCount

您也可以这样做:-

public Process getProcessWithMaxCPUUsage()
    {
        const int delay = 500;
        Process[] processes = Process.GetProcesses();

        var counters = new List<PerformanceCounter>();

        foreach (Process process in processes)
        {
            var counter = new PerformanceCounter("Process", "% Processor Time", process.ProcessName);
            counter.NextValue();
            counters.Add(counter);
        }
        System.Threading.Thread.Sleep(delay);
        //You must wait(ms) to ensure that the current
        //application process does not have MAX CPU
        int mxproc = -1;
        double mxcpu = double.MinValue, tmpcpu;
        for (int ik = 0; ik < counters.Count; ik++)
        {
            tmpcpu = Math.Round(counters[ik].NextValue(), 1);
            if (tmpcpu > mxcpu)
            {
                mxcpu = tmpcpu;
                mxproc = ik;
            }

        }
        return processes[mxproc];
    }

用法:-

static void Main()
    {
        Process mxp=getProcessWithMaxCPUUsage();
        Console.WriteLine(mxp.ProcessName);
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top