Measure a process without losing its identity
Calculate a CPU rate from two observations while rejecting PID reuse and invalid intervals.
CPU time is a cumulative counter
A process with a high CPU-seconds value may simply have been running for a long time. To estimate recent utilization, subtract two counter observations and divide by elapsed time. This lesson reports the process's share of the whole host: divide by the logical processor count as well, so fully occupying one processor on a four-processor host produces 25 percent.
The counter may include execution across several processors, so its delta can exceed wall-clock seconds. The upper bound for this host-normalized convention is elapsed seconds multiplied by logical processors. Keep the result unrounded until presentation; a boundary comparison should not depend on an earlier formatting decision.
A PID alone is not enough
Different hosts reuse process IDs, and the same host can reuse an ID after a process exits. Keep host, PID and creation time together. Equivalent timestamp offsets identify the same instant; normalize aware datetimes to UTC before comparing them. A changed start time invalidates the pair even if the process name and PID look familiar.
Reject naive timestamps, zero or reversed observation intervals, decreasing counters, booleans and non-finite values. Return None for an unusable sample pair rather than a fabricated zero-percent reading. An invalid logical processor count is a caller policy error and raises ValueError separately.
This calculation works on supplied observations and does not inspect the host OS. Real collectors must additionally define sampling accuracy, process lifetime and how their platform's counters map to this convention.
before, after, seconds, logical_cpus = 10, 12, 2, 4
print(100 * (after - before) / (seconds * logical_cpus))
Put it into practice.
Define process_rate(before, after, logical_cpus). Require positive integer non-bool logical_cpus, otherwise ValueError. Samples contain host, pid, started_at, at, cpu_seconds. Match normalized host, positive integer non-bool PID and the UTC instant of started_at. All timestamps must be offset-aware ISO strings. Require positive elapsed observation time and finite nonnegative numeric non-bool counters; their delta must be 0..elapsed*logical_cpus. Return 100*delta/(elapsed*logical_cpus), unrounded. Return None for mismatched identity, missing/invalid sample values or invalid intervals/counters.
See an explained solution
from datetime import datetime, timezone
import math
def process_rate(before, after, logical_cpus):
if type(logical_cpus) is not int or logical_cpus<=0:raise ValueError("Invalid processor count")
def stamp(value):
result=datetime.fromisoformat(value)
if result.tzinfo is None:raise ValueError("Timestamp needs an offset")
return result.astimezone(timezone.utc)
try:
identity=lambda row:(row["host"].strip().casefold(),row["pid"],stamp(row["started_at"]))
if type(before["pid"]) is not int or type(after["pid"]) is not int or before["pid"]<=0 or after["pid"]<=0 or identity(before)!=identity(after):return None
seconds=(stamp(after["at"])-stamp(before["at"])).total_seconds()
counters=[before["cpu_seconds"],after["cpu_seconds"]]
if seconds<=0 or any(type(v) not in (int,float) or not math.isfinite(v) or v<0 for v in counters):return None
delta=counters[1]-counters[0]
if delta<0 or delta>seconds*logical_cpus:return None
return 100*delta/(seconds*logical_cpus)
except (KeyError,TypeError,ValueError,AttributeError):
return None
if __name__ == "__main__":
a={"host":"node-a","pid":410,"started_at":"2026-11-17T10:00:00Z","at":"2026-11-17T12:00:00Z","cpu_seconds":10}
b=dict(a,at="2026-11-17T12:00:02Z",cpu_seconds=12)
print(process_rate(a,b,4))
The formula measures host-normalized CPU only for the same process instance across a valid interval. Identity and numeric checks prevent convincing-looking but meaningless percentages.