问题
[My Attempts]
Already went through
How to get the CPU Usage in C#? But "_Total" Instance of Processor would give me total consumption of CPU as opposed to specifc application or 'process'
In a C# Program, I am trying to get the CPU usage percentage of the application but it always shows 100
What exactly is CPU Time in task manager? , explains it but does not say how to retrive this value.
After referring http://social.technet.microsoft.com/wiki/contents/articles/12984.understanding-processor-processor-time-and-process-processor-time.aspx
I got that
TotalProcessorTimeCounter = new PerformanceCounter("Process", "% Processor Time", processName);
has a baseline of (No.of Logical CPU*100) Basically, this does not give me a scale of 100% over CPU consumed.
Tried digging around task manager and found that Task manger->Processor-> CPU Usage is on a scale of 100.
Processor\% Processor Time object does not take process name as input. it only has '_Total' as an input.
[Question]
How do I get this data(CPU consumption) using performance counters over a scale of 100 for a particular process for a multi-core system?
回答1:
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;
回答2:
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.
回答3:
If you use this, you can get the same result with the task manager :
cpuCounter = new PerformanceCounter(
"Processor Information",
"% Processor Utility",
"_Total",
true
);
来源:https://stackoverflow.com/questions/35288853/cpu-usage-in-task-manager-using-performance-counters