Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

process - c# calculate CPU usage for a specific application

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...
");
            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:

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.

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.

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

...  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 appName for the other counters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...