How to get the CPU Usage in C#?

后端 未结 10 2203
醉酒成梦
醉酒成梦 2020-11-22 06:22

I want to get the overall total CPU usage for an application in C#. I\'ve found many ways to dig into the properties of processes, but I only want the CPU usage of the proce

10条回答
  •  我寻月下人不归
    2020-11-22 07:08

    After spending some time reading over a couple different threads that seemed pretty complicated I came up with this. I needed it for an 8 core machine where I wanted to monitor SQL server. For the code below then I passed in "sqlservr" as appName.

    private static void RunTest(string appName)
    {
        bool done = false;
        PerformanceCounter total_cpu = new PerformanceCounter("Process", "% Processor Time", "_Total");
        PerformanceCounter process_cpu = new PerformanceCounter("Process", "% Processor Time", appName);
        while (!done)
        {
            float t = total_cpu.NextValue();
            float p = process_cpu.NextValue();
            Console.WriteLine(String.Format("_Total = {0}  App = {1} {2}%\n", t, p, p / t * 100));
            System.Threading.Thread.Sleep(1000);
        }
    }
    

    It seems to correctly measure the % of CPU being used by SQL on my 8 core server.

提交回复
热议问题