Name of the process with highest cpu usage

前端 未结 8 1229
栀梦
栀梦 2021-01-18 08:05

I have a Samurize config that shows a CPU usage graph similar to Task manager.

How do I also display the name of the process with the current highest CPU usage per

相关标签:
8条回答
  • 2021-01-18 08:11
    Process.TotalProcessorTime
    

    http://msdn.microsoft.com/en-us/library/system.diagnostics.process.totalprocessortime.aspx

    0 讨论(0)
  • 2021-01-18 08:13

    You can also do it this way :-

    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];
        }
    

    Usage:-

    static void Main()
        {
            Process mxp=getProcessWithMaxCPUUsage();
            Console.WriteLine(mxp.ProcessName);
        }
    
    0 讨论(0)
  • 2021-01-18 08:15

    You might be able to use Pmon.exe for this. You can get it as part of the Windows Resource Kit tools (the link is to the Server 2003 version, which can apparently be used in XP as well).

    0 讨论(0)
  • 2021-01-18 08:19

    What you want to get its the instant CPU usage (kind of)...

    Actually, the instant CPU usage for a process does not exists. Instead you have to make two measurements and calculate the average CPU usage, the formula is quite simple:

    AvgCpuUsed = [TotalCPUTime(process,time2) - TotalCPUTime(process,time1)] / [time2-time1]

    The lower Time2 and Time1 difference is, the more "instant" your measurement will be. Windows Task Manager calculate the CPU use with an interval of one second. I've found that is more than enough and you might even consider doing it in 5 seconds intervals cause the act of measuring itself takes up CPU cycles...

    So, first, to get the average CPU time

        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;
    }
    

    now, for the "instant" CPU load you'll need an specialized class:

     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;
        }
      }
    }
    

    You should call that class from a timer (or whatever interval method you like) for each process you want to monitor, if you want all the processes just use the Process.GetProcesses static method

    0 讨论(0)
  • 2021-01-18 08:26

    Thanks for the formula, Jorge. I don't quite understand why you have to divide by the number of cores, but the numbers I get match the Task Manager. Here's my powershell code:

    $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
    
    0 讨论(0)
  • 2021-01-18 08:28

    Somehow

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

    wasn't getting the CPU information from the remote machine. I had to come up with this.

    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

    0 讨论(0)
提交回复
热议问题