import sys
# this package needs to be installed with the distro package manager
# or via `pip install --user psutil`
import psutil
CPUSET = [4, 5, 6, 7] # indices of hardware threads, 0,1,2,3 or 4,5,6,7 are 4 half-cores on an i7
qemu = psutil.Popen(sys.argv[1:])
try:
qemu.wait(15.0)
sys.exit(1) # exit if QEMU exited
except psutil.TimeoutExpired as ex:
pass # continue if QEMU still running
threads = qemu.threads()
threads.sort(key=lambda thread: thread.user_time + thread.system_time, reverse=True)
for thread in threads:
# assign threads to cores in order of decreasing activity
cpu = CPUSET.pop(0)
psutil.Process(thread.id).cpu_affinity([cpu])
print("Thread %d bound to CPU #%d" % (thread.id, cpu))
if not CPUSET: # until we run out of defined cores
break
qemu.wait() # wait for QEMU to finish