Documenting CPU Load for Running Processes

by Apr 16, 2013

Get-Process can easily return the CPU load for each running process, but this information by itself is not very useful:

Get-Process | Select-Object -Property Name, CPU, Description

(Note that if you run this code from an elevated PowerShell, you see information for all processes. Else, you can only examine CPU load for your own processes.)

The CPU property returns the number of seconds the particular process has utilized the CPU. A high number does not necessarily indicate high CPU usage, though, because this all depends on how long a process has been running. CPU is an accumulated number, so the longer a process runs, the higher the CPU load is.

A much better indicator for CPU-intensive processes is to set CPU load in relation with process runtime and calculate the average CPU load percentage.

Here’s a sample that illustrates how you can do that:

$CPUPercent = @{
  Name = 'CPUPercent'
  Expression = {
    $TotalSec = (New-TimeSpan -Start $_.StartTime).TotalSeconds
    [Math]::Round( ($_.CPU * 100 / $TotalSec), 2)
  }
}



Get-Process | 
 Select-Object -Property Name, CPU, $CPUPercent, Description |
 Sort-Object -Property CPUPercent -Descending |
 Select-Object -First 4

This piece of code returns the top 4 CPU-intensive running processes:

As you can see from the sample output, ISE ranks 2 although the total CPU time is higher than WinWord. That’s because ISE was running much longer than WinWord, so the load percentage is lower.

The code uses a hash table to create a new calculated property called CPUPercent. To calculate the value, New-Timespan determines the total seconds a process is running. Then, the accumulated CPU load is divided by that number and returns the CPU load percentage per second.

Note also how the result is rounded. By rounding a numeric result, you can control the digits after the decimal without changing the numeric data type, so the result can still be sorted correctly.

ReTweet this Tip!