问题
Is it possible to print the current CPU usage for each core in the system?
This is what I have so far using powershell:
Get-WmiObject -Query "select Name, PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor"
回答1:
It can be be done using the following powershell command:
(Get-WmiObject -Query "select Name, PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor") | foreach-object { write-host "$($_.Name): $($_.PercentProcessorTime)" };
Also you could create a file called get_cpu_usage.ps1
with the contents:
while ($true)
{
$cores = (Get-WmiObject -Query "select Name, PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor")
$cores | foreach-object { write-host "$($_.Name): $($_.PercentProcessorTime)" };
Start-Sleep -m 200
}
Then run it using:
powershell -executionpolicy bypass "get_cpu_usage.ps1"
回答2:
As an alternative, you can use Get-Counter
command.
For example:
Get-Counter -Counter '\Processor(*)\% Processor Time' -Computer $desktop | select -ExpandProperty CounterSamples
From my testing it's about 4 times faster (atleast on my machine) than querying WMI.
EDIT:
After testing some more, repeated uses of the query are faster (got mean of 284 ms
) because Get-Counter
needs minimum of 1 second to get the samples.
回答3:
In Powershell Core 6 the commands have changed.
(Get-CimInstance -Query "select Name, PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor") | foreach-object { write-host "$($_.Name): $($_.PercentProcessorTime)" };
The script would look like this in Powershell Core 6.
while ($true) {
$cores = (Get-CimInstance -Query "select Name, PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor")
$cores | foreach-object { write-host "$($_.Name): $($_.PercentProcessorTime)" };
Start-Sleep -m 1000
[System.Console]::Clear()
}
I just like a screen clear between updates. :)
来源:https://stackoverflow.com/questions/38384658/get-cpu-usage-for-each-core-using-the-windows-command-line