Using PowerShell to find the virtual processor to logical processor ratio of Hyper-V

For as long as I can remember – I have been talking to people about supported / optimal virtual processor to logical processor ratios with Hyper-V.  Or – said with less technical jargon – how many virtual machines, with how many virtual processors, should you run on any given physical computer?

Today our documented guidance is that we support up to 8 virtual processors for each logical processor in the physical computer – and that for best performance under most reasonable circumstances you should aim for a ratio of 4 virtual processors per logical processor in the physical computer.

The problem with all of this?  We do not provide any simple way to find out what your current ratio is.

When I realized this – I simultaneously realized that I did not know what the virtual processor to logical processor ratio was on any of my computers.  As such – I decided that I needed to write a script to do this.

Now – in the past some of my readers have accused me of not being a “real PowerShell scripter”, and that I was “writing VBscript style PowerShell”.  Today I would like to try and set the record straight on this accusation.  Because as I started looking into this – I realized that this did not need to be a script at all.  No! It can be done with one (nearly incomprehensible) line of PowerShell code.  Which goes as follows:

write-host (@(gwmi -ns root\virtualization MSVM_Processor).count / (@(gwmi Win32_Processor) | measure -p NumberOfLogicalProcessors -sum).Sum) "virtual processor(s) per logical processor" -f yellow

When I ran this on my main Hyper-V server at home – I got the following result:

image

Neat! I am practically right on the sweet spot!

But what does this line of code do – and how does it work?  Well – there are a couple of things to know:

  • For each virtual processor for each currently running virtual machine there is an instance of the MSVM_Processor WMI object on the system.  So to figure out how many virtual processors are currently running – you just have to count how many instances of this WMI object are currently present on the system.
  • Summing up the NumberOfLogicalProcessors property of the Win32_Processor object will given you the other side of the calculation – namely how many logical processors are present in the system.
  • In order to keep the one line of code as short as possible – I have used every PowerShell abbreviation that I know of (gwmi for Get-WMIObject, –ns for –namespace, measure for measure-object, –p for –property, –f for –foregroundColor)

Cheers,
Ben