如何在命令行上获取Windows Pid的cpu%使用率?

时间:2016-05-11 03:05:42

标签: java windows cpu pid

我知道通过进程名称获取此方法的许多方法,但我有许多具有相同名称(Java)的进程,因此需要使用PID。

很高兴使用任何可以完成此任务的工具/语言。

最终这将使用Cygwin进行调用。 感谢

3 个答案:

答案 0 :(得分:1)

这个VB脚本似乎可以解决这个问题,在命令行上传递pid: (可以省略循环的初始化)

For Each Process in GetObject("winmgmts:").ExecQuery("Select * from Win32_Process where Handle =  " & WScript.Arguments.Item(0) &  "")
 WScript.echo Process.Handle & " " & Process.name & " " & CPUUSage(Process.Handle) & " %"   
Next

Function CPUUSage( ProcID )
  On Error Resume Next

Set objService = GetObject("Winmgmts:{impersonationlevel=impersonate}!\Root\Cimv2")

For Each objInstance1 in objService.ExecQuery("Select * from Win32_PerfRawData_PerfProc_Process where IDProcess = '" & ProcID & "'")
    N1 = objInstance1.PercentProcessorTime
    D1 = objInstance1.TimeStamp_Sys100NS
    Exit For
Next

 WScript.Sleep(2000)

For Each perf_instance2 in objService.ExecQuery("Select * from Win32_PerfRawData_PerfProc_Process where IDProcess = '" & ProcID & "'")
    N2 = perf_instance2.PercentProcessorTime
    D2 = perf_instance2.TimeStamp_Sys100NS
    Exit For
Next

Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20
strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Processor", "WQL", _
                                      wbemFlagReturnImmediately + wbemFlagForwardOnly)

For Each objItem In colItems
    Nc = objItem.NumberOfLogicalProcessors
Next

' CounterType - PERF_100NSEC_TIMER_INV
' Formula - (1- ((N2 - N1) / (D2 - D1))) x 100
Nd = (N2 - N1)
Dd = (D2 - D1)
' Nd/Dd = number of cores used.
' ((Nd/Dd)/Nc) * 100 = % of whole box used
PercentProcessorTime = ((Nd/Dd)/Nc)*100

CPUUSage = Round(PercentProcessorTime ,2)
End Function

例如(在cygwin中)如果上面的文件是cpu.vbs: cmd / c cscript / nologo cpu.vbs 64940

答案 1 :(得分:0)

您可以使用快速PowerShell脚本:

$searchPid = 6204
get-process | where-object Id -eq $searchPid | select-object CPU

在命令行中,您应该只需要:

powershell "get-process | where-object Id -eq 6204 | select-object CPU"

<强>更新

如注释中所述,get-process仅返回进程在几秒钟内使用的CPU时间,因此它对CPU的使用百分比没有帮助。看起来WMI调用应该为您获得该百分比:

powershell "get-wmiobject Win32_PerfFormattedData_PerfProc_Process | where-object idprocess -eq 6204 | select PercentProcessorTime"

答案 2 :(得分:0)

您可以使用psTools

尝试以下命令
pslist <pid> -s