Measure CPU across two samples
Calculate host-normalised CPU utilisation while rejecting invalid intervals and process reuse.
Turn a counter into a rate
A single cumulative CPU reading cannot tell you how busy a process is now. Compare two readings for the same process instance. Subtract the earlier CPU seconds from the later CPU seconds, then divide by elapsed wall-clock seconds.
This lesson defines host-normalised utilisation: divide again by the host's logical processor count and multiply by 100. If a process consumes four CPU seconds over two wall-clock seconds on a four-logical-processor host, the result is 50 percent. Other tools may use a per-core convention; name and document yours.
Check identity before subtraction
Require ComputerName, Id, and StartTime to match. If they differ, return no result ($null) because these samples do not describe the same instance. Do not turn missing continuity into zero utilisation.
Reject non-positive intervals, fewer than one logical processor, and a counter that moves backwards. A decrease can indicate incompatible data or reset state. Avoid silently clamping it to zero. Real sampling also needs trustworthy timestamps and enough precision for the interval; the supplied exercise passes the elapsed interval explicitly.
Test the edge, not just the formula
The checks include zero CPU growth, a reused PID, a different computer, invalid denominators, and a decreasing counter. A reusable helper should explain where it cannot calculate a meaningful value. No real process is sampled by this exercise.
Go deeper
$before=10; $after=14; $seconds=2; $logical=4
100 * ($after-$before) / ($seconds*$logical)
Put it into practice.
Define Get-ProcessCpuPercent(Before, After, Seconds, LogicalProcessors). Return the host-normalised percentage for matching ComputerName/Id/StartTime. Return $null for different identities. Throw for Seconds <= 0, LogicalProcessors < 1, or decreasing CPU on a matching instance.
See an explained solution
function Get-ProcessCpuPercent {
param($Before,$After,[double]$Seconds,[int]$LogicalProcessors)
if($Seconds -le 0 -or $LogicalProcessors -lt 1) { throw 'Invalid interval or processor count' }
if($Before.ComputerName -ne $After.ComputerName -or $Before.Id -ne $After.Id -or $Before.StartTime -ne $After.StartTime) { return $null }
$change=[double]$After.CPU - [double]$Before.CPU
if($change -lt 0) { throw 'Counter moved backwards' }
100 * $change / ($Seconds * $LogicalProcessors)
}
A rate requires matching identity and a valid interval. Dividing by logical processors makes 100 percent represent all of this host’s logical CPU capacity.