Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# get process with high CPU usage

Tags:

c#

cpu

I am looking for a way to get the process name which is consuming the highest CPU. Here is my code which gets the process's CPU usage

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

    // will always start at 0
    float firstValue = cpuCounter.NextValue();
    System.Threading.Thread.Sleep(1000);
    // now matches task manager reading
    int secondValue = (int)cpuCounter.NextValue();
}

For whole system CPU, I have

PerformanceCounter cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";

// will always start at 0
float firstValue = cpuCounter.NextValue();
System.Threading.Thread.Sleep(1000);
// now matches task manager reading
int secondValue = (int)cpuCounter.NextValue();

Is there any way so that I can find most CPU consuming process ?

like image 553
Harshit Avatar asked Sep 17 '15 11:09

Harshit


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

Is C programming hard?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.


1 Answers

The code gets a list of all runnig processes and assigns a PerformanceCounter to each of them. It then queries the counters with an intervall of 1000ms. Only the values with > 0% are outputted in descending order to the console.

using System;
using System.Linq;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;

namespace ProcessCount
{
    static class Program
    {
        static void Main()
        {
            var counterList = new List<PerformanceCounter>();

            while (true)
            {
                var procDict = new Dictionary<string, float>();

                Process.GetProcesses().ToList().ForEach(p =>
                {
                    using (p)
                        if (counterList
                            .FirstOrDefault(c => c.InstanceName == p.ProcessName) == null)
                            counterList.Add(
                                new PerformanceCounter("Process", "% Processor Time",
                                    p.ProcessName, true));
                });

                counterList.ForEach(c =>
                {
                    try
                    {
                        // http://social.technet.microsoft.com/wiki/contents/
                        // articles/12984.understanding-processor-processor-
                        // time-and-process-processor-time.aspx

                        // This value is calculated over the base line of 
                        // (No of Logical CPUS * 100), So this is going to be a 
                        // calculated over a baseline of more than 100. 
                        var percent = c.NextValue() / Environment.ProcessorCount;
                        if (percent == 0)
                            return;

                        // Uncomment if you want to filter the "Idle" process
                        //if (c.InstanceName.Trim().ToLower() == "idle")
                        //    return;

                        procDict[c.InstanceName] = percent;
                    }
                    catch (InvalidOperationException) { /* some will fail */ }
                });

                Console.Clear();
                procDict.OrderByDescending(d => d.Value).ToList()
                    .ForEach(d => Console.WriteLine("{0:00.00}% - {1}", d.Value, d.Key));

                Thread.Sleep(1000);
            }
        }
    }
}
like image 93
KarmaEDV Avatar answered Sep 23 '22 13:09

KarmaEDV