Name of the process with highest cpu usage

前端 未结 8 1296
栀梦
栀梦 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:13

    You can also do it this way :-

    public Process getProcessWithMaxCPUUsage()
        {
            const int delay = 500;
            Process[] processes = Process.GetProcesses();
    
            var counters = new List();
    
            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);
        }
    

提交回复
热议问题