Get CPU Usage of a Process from Command Line

Here’s some kung-fu command-line that I hacked up this morning while brainstorming a few issues I had come across.

Basically, I needed to figure out how to keep an eye on a particular process’ CPU time. Sure, you can watch this from Task Manager but this method is better (IMHO) because I can save the log output for future analysis.
For example, I can launch my program and then start this batch file to monitor it’s CPU time throughout it’s life.

When the process terminates, the batch file terminates as well.

Here’s the batch file code:

@echo off
: report processor time for given process until process exits (could be expanded to use a PID to be more
: precise)
:
: Usage:  foo.cmd <processname>
set process=%~1
echo Press CTRL-C To Stop...
:begin
for /f tokens=2 delims=, %%c in ('typeperf "\Process(%process%)\% Processor Time" -si 1 -sc 1 ^| find /V ') do (
if %%~c==-1 (
goto :end
) else (
echo %%~c%%
goto begin
)
)
:end
echo Process seems to have terminated.

Example Output:

Here’s a VBscript that is little different but still reports CPU time for every process. Good starting point if you need to hack something up.

I previously posted up a pretty lengthy entry on using WMIC to find CPU usage in the event you might be interested in that method as well.

strComputer =.
Set objWMIService = GetObject(winmgmts: & strComputer & rootcimv2)
Set colProcess = objWMIService.ExecQuery(Select * from Win32_PerfFormattedData_PerfProc_Process,,48)
For Each obj in colProcess
If obj.Name <> Idle  And obj.Name <> _Total Then
        WScript.echo obj.Name & , & obj.PercentProcessorTime
End If
Next

Published by

Rich

Just another IT guy.

Leave a Reply

Your email address will not be published. Required fields are marked *