Skip to content

Instantly share code, notes, and snippets.

@MatiasVara
Created September 25, 2023 08:32
Show Gist options
  • Save MatiasVara/3f7f1f22b58261480f8fd5ec2ed55b7e to your computer and use it in GitHub Desktop.
Save MatiasVara/3f7f1f22b58261480f8fd5ec2ed55b7e to your computer and use it in GitHub Desktop.
Script to pin vcpus to physical cpus for QEMU by using QMP (based on https://patchwork.kernel.org/project/qemu-devel/patch/[email protected]/)
import asyncio
from qemu.qmp import QMPClient
import argparse
from subprocess import call
import os
async def main():
parser = argparse.ArgumentParser(description='Pin QEMU vCPUs to physical CPUs')
parser.add_argument('-s', '--server', type=str, required=True, help='QMP server path or address:port')
parser.add_argument('cpu', type=int, nargs='+', help='Physical CPUs IDs')
args = parser.parse_args()
qmp = QMPClient('my-vm-nickname')
await qmp.connect(args.server)
devnull = open(os.devnull, 'w')
res = await qmp.execute('query-cpus-fast')
for vcpu in res:
vcpuid = vcpu['cpu-index']
tid = vcpu['thread-id']
cpuid = args.cpu[vcpuid % len(args.cpu)]
print(f"Pin vCPU {vcpuid} (tid {tid}) to physical CPU {cpuid}") #.format(vcpuid, tid, cpuid))
try:
call(['taskset', '-pc', str(cpuid), str(tid)], stdout=devnull)
except OSError:
print(f"Failed to pin vCPU{vcpuid} to CPU{cpuid}") #.format(vcpuid, cpuid)
await qmp.disconnect()
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment