Reputation:
I been looking at PerformanceCounter Class for monitoring system performance. I have figured out how to call built in counters. What I'm struggling with is understanding the values that I get back and how compare those values to what I can see in Task Manager.
So far I have successfully been able to monitor available RAM in MB and it correctly corresponded to value in Task Manager.
first I created PerformanceCounter
myMemoryCounter = new PerformanceCounter("Memory", "Available MBytes", true);
Then I put the following line inside a loop.
Console.WriteLine("Value" + myMemoryCounter.NextSample().RawValue.ToString());
When looking at counters for processor, I'm not able to make connection to % CPU Utilization that can be observed in Task Manager.
Do I need to have multiple counters and compute the value or is there easier way?
Update:
Looking at question What is the correct Performance Counter to get CPU and Memory Usage of a Process? it just describes which counter to use but not how to convert results to percentage?
NextSample().RawValue
returns long data type and I need to know how to convert it to percentage.
Using the following code
var _myCPUCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
Console.WriteLine("CPU " + _myCPUCounter.NextSample().RawValue.ToString("0.000"));
I get this value 1794607539062
how do I convert that to percentage?
Upvotes: 3
Views: 5808
Reputation: 21
// TRY THIS
public class MyCPU
{
// This method that will be called when the thread is started
public void Info()
{
/*
* CPU time (or process time) is the amount of time for which a central processing unit (CPU) was used for processing instructions of a computer program or operating system
*/
PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName);
for (int i64 = 0; i64 < 100; ++i64)
{
Console.WriteLine("CPU: " + (cpuCounter.NextValue() / Environment.ProcessorCount) + " %");
}
}
};
Upvotes: 2
Reputation: 21
According to the source, for the CPU counter, which is type Timer100NsInverse
, the calculator method returns:
(1f - ((float)(newSample.RawValue - oldSample.RawValue))/(float)(newSample.TimeStamp - oldSample.TimeStamp)) * 100.0f;
Note it needs two samples.
See CounterSampleCalculator.cs
which you can find in multiple places on the web. It can show you all the calculations for all the types. But you can just call the Calculate
methods, or NextValue()
as already described.
Upvotes: 0