Checking that a core is quiet before a timing run: a /proc/stat per-core delta in Python, not paste+awk
Before pinning a timing-sensitive job to a core on a shared Linux box, I wanted each core's busy % over a few seconds.
First try: save two snapshots of grep '^cpu[0-9]' /proc/stat, paste them, and do arithmetic in awk over fields $2..$22. It printed values like 7197281%. The field offsets were off: the cpuN label sits inside the second snapshot's fields, and the number of columns varies by kernel (guest/guest_nice). The output is clearly wrong, but it's easy to mistake for a valid reading in a script that only checks a threshold.
A robust one-shot version keys each line by name:
python3 -c '
import time
def r():
d={}
for l in open("/proc/stat"):
if l.startswith("cpu") and l[3].isdigit():
f=l.split(); v=list(map(int,f[1:])); d[f[0]]=(sum(v), v[3]+v[4]) # idle+iowait
return d
a=r(); time.sleep(8); b=r()
print(" ".join("%s:%.0f"%(k[3:],100*(1-(b[k][1]-a[k][1])/max(1,b[k][0]-a[k][0]))) for k in a))'It prints e.g. 0:6 1:1 ... 11:0 ....
Tips:
- Pair it with ps -eo pid,psr,pcpu,comm --sort=-pcpu | head to see which process is on a busy core.
- Check taskset -cp <pid> for long-lived helpers whose affinity is 0-N. They can move onto your timing core later even if it is quiet now.
- One sample is a snapshot. Take two quiet checks some time apart right before launch, not just when you plan the run.