CPU Usage in Task Manager using Performance Counters

前端 未结 3 1289
南方客
南方客 2021-01-17 06:22

[My Attempts]

Already went through

  1. How to get the CPU Usage in C#? But \"_Total\" Instance of Processor would give me total consumption of CPU as o

相关标签:
3条回答
  • 2021-01-17 06:44

    If you use this, you can get the same result with the task manager :

    cpuCounter = new PerformanceCounter(
            "Processor Information",
            "% Processor Utility",
            "_Total",
            true
        );
    
    0 讨论(0)
  • 2021-01-17 06:45

    This gives me the exact figure you get on Task Manager (in the Details tab), is this what you want?

    // Declare the counter somewhere
    var process_cpu = new PerformanceCounter(
                                       "Process", 
                                       "% Processor Time", 
                                       Process.GetCurrentProcess().ProcessName
                                            );
    // Read periodically
    var processUsage = process_cpu.NextValue() / Environment.ProcessorCount;
    
    0 讨论(0)
  • 2021-01-17 06:46

    After reading this performance counter document https://social.technet.microsoft.com/wiki/contents/articles/12984.understanding-processor-processor-time-and-process-processor-time.aspx I realized that the correct approach to getting this value is actually to take 100 and subtract the idle time of all processors.

    % Processor Time is the percentage of elapsed time that the processor spends to execute a non-Idle thread.

    var allIdle = new PerformanceCounter(
        "Processor", 
        "% Idle Time", 
        "_Total"
    );
    
    int cpu = 100 - allIdle;
    

    This gives a value very close to what Task Manager displays and perhaps is only different at some points due to rounding or the specific time of when the counter is polled.

    0 讨论(0)
提交回复
热议问题