c# 计算特定应用程序的 CPU 使用率

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1277556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:35:13  来源:igfitidea点击:

c# calculate CPU usage for a specific application

c#processcpu-usage

提问by Grant

I'm trying to figure out how to get the CPU usage for a particular process but can only find information relating to overallCPU usage.

我试图弄清楚如何获取特定进程的 CPU 使用率,但只能找到与整体CPU 使用率相关的信息。

Does anyone know how to extract the current CPU usage in percentage terms for a specific application?

有谁知道如何提取特定应用程序当前 CPU 使用率百分比?

采纳答案by Erich Mirabal

Performance Counters - Process - % Processor Time.

性能计数器 - 进程 - % 处理器时间。

Little sample code to give you the idea:

给你这个想法的小示例代码:

using System;
using System.Diagnostics;
using System.Threading;

namespace StackOverflow
{
    class Program
    {
        static void Main(string[] args)
        {
            PerformanceCounter myAppCpu = 
                new PerformanceCounter(
                    "Process", "% Processor Time", "OUTLOOK", true);

            Console.WriteLine("Press the any key to stop...\n");
            while (!Console.KeyAvailable)
            {
                double pct = myAppCpu.NextValue();
                Console.WriteLine("OUTLOOK'S CPU % = " + pct);
                Thread.Sleep(250);
            }
        }
    }
}

Notes for finding the instance based on Process ID:

根据 Process ID 查找实例的注意事项

I do not know of any better way, and hopefully somebody does. If not, here is one way you can find the right instance name for your process given the Process ID and process name.

我不知道有什么更好的方法,希望有人知道。如果没有,这里是一种方法,您可以根据进程 ID 和进程名称为您的进程找到正确的实例名称。

There is another Performance Counter (PC) called "ID Process"under the "Process"family. It returns the PID for the instance. So, if you already know the name (i.e. "chrome" or "myapp"), you can then test each instance until you find the match for the PID.

"ID Process""Process"系列下还有另一个性能计数器 (PC) 。它返回实例的 PID。因此,如果您已经知道名称(即“chrome”或“myapp”),那么您可以测试每个实例,直到找到匹配的 PID。

The naming is simple for each instance: "myapp" "myapp#1" "myapp#2" ... etc.

每个实例的命名都很简单:“myapp”“myapp#1”“myapp#2”……等等。

...  new PerformanceCounter("Process", "ID Process", appName, true);

Once the PC's value equals the PID, you found the right appName. You can then use that appNamefor the other counters.

一旦 PC 的值等于 PID,您就找到了正确的appName. 然后您可以将其appName用于其他计数器。

回答by Muhammad Mubashir

PerformanceCounter ProcessCPUCounter = new PerformanceCounter();
            ProcessCPUCounter.CategoryName = "Process";
            ProcessCPUCounter.CounterName = "% Processor Time";
            ProcessCPUCounter.InstanceName = "TestServiceName"; 
            ProcessCPUCounter.ReadOnly = true;

t3 = new Timer();
            t3.Tick += new EventHandler(ProcessCPUThread); // Everytime t3 ticks, th2_Tick will be called
            t3.Interval = (1000) * (1);              // Timer will tick evert second
            t3.Enabled = true;                       // Enable the t3
            t3.Start(); 

private void ProcessCPUThread(object sender, EventArgs e)
        {
            try
            {         
                Int32 processCPU = Convert.ToInt32( ProcessCPUCounter.NextValue());

                tbCPUperPrcocess.Text = Convert.ToString(processCPU / Environment.ProcessorCount);
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message.ToString());
            }
        }

回答by rayzinnz

A method to calculate processor usage for a single process without using PerformanceCounter.

一种在不使用 PerformanceCounter 的情况下计算单个进程的处理器使用情况的方法。

using System;
using System.Diagnostics;

namespace cpuusage
{
    class Program
    {
        private static DateTime lastTime;
        private static TimeSpan lastTotalProcessorTime;
        private static DateTime curTime;
        private static TimeSpan curTotalProcessorTime;

        static void Main(string[] args)
        {
            string processName = "OUTLOOK";

            Console.WriteLine("Press the any key to stop...\n");
            while (!Console.KeyAvailable)
            {
                Process[] pp = Process.GetProcessesByName(processName);
                if (pp.Length == 0)
                {
                    Console.WriteLine(processName + " does not exist");
                }
                else
                {
                    Process p = pp[0];
                    if (lastTime == null || lastTime == new DateTime())
                    {
                        lastTime = DateTime.Now;
                        lastTotalProcessorTime = p.TotalProcessorTime;
                    }
                    else
                    {
                        curTime = DateTime.Now;
                        curTotalProcessorTime = p.TotalProcessorTime;

                        double CPUUsage = (curTotalProcessorTime.TotalMilliseconds - lastTotalProcessorTime.TotalMilliseconds) / curTime.Subtract(lastTime).TotalMilliseconds / Convert.ToDouble(Environment.ProcessorCount);
                        Console.WriteLine("{0} CPU: {1:0.0}%",processName,CPUUsage * 100);

                        lastTime = curTime;
                        lastTotalProcessorTime = curTotalProcessorTime;
                    }
                }

                Thread.Sleep(250);
            }
        }
    }
}

You could loop through the processes to pick which one, or if you already know the id, simply use this command instead of GetProcessesByName()

您可以遍历进程以选择哪个进程,或者如果您已经知道 id,只需使用此命令而不是 GetProcessesByName()

Process p = Process.GetProcessById(123);

回答by shytikov

I have compiled information from several answers (most noticeably this one) and come up with following code that able to get information about current process's CPU and RAM usage based on performance counter information provided by Windows:

我从几个答案(最明显的是这个)中汇编了信息,并提出了以下代码,该代码能够根据 Windows 提供的性能计数器信息获取有关当前进程的 CPU 和 RAM 使用情况的信息:

public object GetUsage()
{
    // Getting information about current process
    var process = Process.GetCurrentProcess();

    // Preparing variable for application instance name
    var name = string.Empty;

    foreach (var instance in new PerformanceCounterCategory("Process").GetInstanceNames())
    {
        if (instance.StartsWith(process.ProcessName))
        {
            using (var processId = new PerformanceCounter("Process", "ID Process", instance, true))
            {
                if (process.Id == (int)processId.RawValue)
                {
                    name = instance;
                    break;
                }
            }
        }
    }

    var cpu = new PerformanceCounter("Process", "% Processor Time", name, true);
    var ram = new PerformanceCounter("Process", "Private Bytes", name, true);

    // Getting first initial values
    cpu.NextValue();
    ram.NextValue();

    // Creating delay to get correct values of CPU usage during next query
    Thread.Sleep(500);

    dynamic result = new ExpandoObject();

    // If system has multiple cores, that should be taken into account
    result.CPU = Math.Round(cpu.NextValue() / Environment.ProcessorCount, 2);
    // Returns number of MB consumed by application
    result.RAM = Math.Round(ram.NextValue() / 1024 / 1024, 2);

    return result;
}

Instance name determined without any hacks or guesses, I'm also taking care about multiple cores.

在没有任何黑客或猜测的情况下确定实例名称,我也在关注多核。

Information retrieved is inline with information I see in process explorer and performance window in VS.

检索到的信息与我在 VS 的进程资源管理器和性能窗口中看到的信息一致。