Reputation: 4662
I am trying to get the total cpu usage every x seconds on our virtual machines. I found this code:
var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
WriteCpuUsageToFile(cpuCounter.NextValue() + "%");
Every time the timer fires, I am getting a value of zero.
2016-03-15T02:29:26 0%
2016-03-15T02:29:45 0%
2016-03-15T02:30:05 0%
2016-03-15T02:30:25 0%
2016-03-15T02:30:45 0%
The server is hitting an average of 20%.
I am allocating ~8 cores to the vm, depending on the vm. Do I need to get the value for a virtual machine differently with C#?
Thanks for the assistance!
Upvotes: 1
Views: 1564
Reputation: 11
Use libvirt api to access host cpu usage, I have made an Python code to put all data into an csv file. Link for the Python code: https://github.com/leonardo329cf/VMMeter-libvirt
Upvotes: 1
Reputation: 28272
While the old answer is interesting, it didn't solve the OP's question.
The problem (found in some screenshot in the comments) was that the OP was instantiating the PerformanceCounter
every time he called NextValue
, so it wasn't letting the counter collect the values.
The correct solution is instantiating the PerformanceCounter
once, and call NextValue()
many times on the same instance.
Old answer kept below for the hopefully interesting information, but it applies to the host, not to the guest:
As explained here: https://msdn.microsoft.com/en-us/library/cc768535(v=bts.10).aspx
Measure guest operating system processor utilization – Traditionally, processor performance can be measured using the “\Processor(*)\% Processor Time” performance monitor counter. This is not an accurate counter for evaluating processor utilization of a guest operating system though because Hyper-V measures and reports this value relative to the number of processors allocated to the virtual machine.
... (lengthy explanation on why it's not a good idea and can actually be a bottleneck, which you can read on the link) ...
To accurately measure the processor utilization of a guest operating system, use the “\Hyper-V Hypervisor Logical Processor(_Total)\% Total Run Time” performance monitor counter on the Hyper-V host operating system. Use the following thresholds to evaluate guest operating system processor utilization using the “\Hyper-V Hypervisor Logical Processor(_Total)\% Total Run Time” performance monitor counter
So I haven't tested this, but
Edit: I actually tested it and it works, so:
var cpuCounter = new PerformanceCounter("Hyper-V Hypervisor Logical Processor"
, "% Total Run Time"
, "_Total", true);
Upvotes: 1