Skip to content

Instantly share code, notes, and snippets.

@ge0rg
Created June 17, 2026 17:25
Show Gist options
  • Select an option

  • Save ge0rg/1206c0bcd6d25c8d33b4355e8703dafe to your computer and use it in GitHub Desktop.

Select an option

Save ge0rg/1206c0bcd6d25c8d33b4355e8703dafe to your computer and use it in GitHub Desktop.
Poll a PID's state at 1ms resolution and aggregate the numbers
#!/usr/bin/env python3
import math
import sys
import time
states = "RSDZTtWXxKWPI"
def get_state(pid):
stat = open(f"/proc/{pid}/stat", "r").read().split(' ')
return stat[2]
def format_stat(k, v, total, absolute=False):
if absolute:
return "%s:%4.1fs" % (k, v/1000)
return "%s:%5.1f" % (k, 100*v/total)
def print_stats(stats, timediff=None):
total = sum(stats.values())
if total == 0:
return ""
absval = timediff is not None
if absval:
postfix = " (%0.1f seconds)" % timediff
else:
postfix = " (%d samples)" % total
return " ".join([format_stat(k, v, total, absval) for k, v in stats.items()][0:5]) + postfix
pid = sys.argv[1]
stats = dict.fromkeys(list(states), 0)
totals = dict.fromkeys(list(states), 0)
t0 = t = time.time()
try:
while True:
dt = time.time()*1000
dt = 1 + math.floor(dt) - dt
time.sleep(0.001*dt)
t_ = time.time()
if int(t) != int(t_):
print(print_stats(stats))
t = t_
stats = dict.fromkeys(list(states), 0)
state = get_state(pid)
stats[state] += 1
totals[state] += 1
except (FileNotFoundError, ProcessLookupError):
print("PID %s not found" % sys.argv[1])
except KeyboardInterrupt:
print()
if t != t0:
print(print_stats(totals))
print(print_stats(totals, timediff=t_ - t0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment