Getting CPU usage of a process in C#

前端 未结 2 523
臣服心动
臣服心动 2021-02-01 10:15

I would like to get CPU usage for a specific process..

This code

total_cpu = new PerformanceCounter(\"Processor\", \"% Processor Time\", \"_Total\");


        
相关标签:
2条回答
  • 2021-02-01 10:56

    Dividing by the processor/core count is what seemed to yield fairly accurate results when comparing against Task Manager.

    To save people time:

    // This will return the process usage as a percent of total processor utilisation.
    var processUsage = process_cpu_usage/nextValue() / Environment.ProcessorCount;
    
    0 讨论(0)
  • 2021-02-01 10:57

    Actually, the Process\% Processor Time\Instance counter returns the % of time that the monitored process uses on % User time for a single processor. So the limit is 100% * the number of processors you have.

    There doesn't seem to be an easy way to compute the value that taskmgr displays using perfmon counters. See this link.

    Also remember the percentage of CPU usage is not a fixed value, but a calculated value:

    ((total processor time at time T2) - (total processor time at time T1) / (T2 - T1))
    

    This means that the values depend on both T2 and T1, so there might be differences between what you see on task manager and what you compute, if T2 and T1 used by Task Manager are slightly different than T2 and T1 used by your program.


    If you are interested, I can provide you some code to retrieve this value using P/Invoke. But'll loose the benefits of Performance Counters (such as monitoring remote processes).

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