I put the following function in my program in python 2.6 and it calls windows functions.
My machine has only two cores so you may need to change that part.
The comments tell you how to see what the current affinity is.
It works "as is" for a single core machine if you set or default to a mask of 1.
def setaffinitymask(pid = None, mask = 1):
""" Set The Affinity Mask of a Windows Process. Affinity Mask is a value between 1-3 where
1 is for core 0, 2 is for core 1, 3 is for both cores (it is a bitmap)
Default sets the Affinity Mask to core 0 only
python process can take any valid process ID. """
import win32api, win32process, win32con
if pid == None:
pid = win32api.GetCurrentProcessId()
if mask == None:
mask = 1
if mask < 1 or mask > 3:
mask = 1
print 'process affinity mask out of range [1..3] setting it to 1'
handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
# see what mask is currently set to
# processAffinityMask, systemAffinityMask = win32process.GetProcessAffinityMask(handle)
# print 'process affinity mask = ', processAffinityMask, ', system affinity mask = ', systemAffinityMask
# set affinity for process to mask value
win32process.SetProcessAffinityMask(handle, mask) # 1=core 0, 2=core 1, 3=both
processAffinityMask, systemAffinityMask = win32process.GetProcessAffinityMask(handle)
#print 'process affinity mask = ', processAffinityMask, ', system affinity mask = ', systemAffinityMask
2Why do you want to do this? Letting the OS decide which CPU/core runs which process it going to be much more efficient. – ChrisF – 2011-07-12T13:24:29.870
1in order to benchmark various programming language aspects – Jonathan – 2011-07-12T14:00:30.913
1That's a good reason - you should have included that information in your question. It's important. – ChrisF – 2011-07-12T14:08:50.440
Motivation isn't essential, but I added it following your advice – Jonathan – 2011-07-12T14:38:46.623
1However, it might be the information someone needs to be able to provide an answer. – ChrisF – 2011-07-12T14:39:28.230