os.sched_setaffinity()
in Python is used to set the CPU affinity mask of the process indicated by the specified process ID. The CPU bind mask of a process defines the set of CPUs it can run on.
Note. This method is only available on some UNIX platforms.
Syntax: os.sched_setaffinity (pid, mask)
Parameter:
pid : The process id of the process whose CPU affinity mask is to be set required. Process’s CPU affinity mask determines the set of CPUs on which it is eligible to run.
A pid of 0 represents the calling process.
mask : An iterable of integers representing the set of CPUs to which the process should be restricted.
Return Type: This method does not return any value.
Code: using the os.sched_setaffinity () method
# Python program to explain the os.sched_setaffinity () method # import of the os module import os # Get the number of processors # in the system # using the method os.cpu_count () print ( "Number of CPUs:" , os.cpu_count ()) # Get a set of processors # on which the process is called # has the right to run. using # os.sched_getaffinity () method # 0 because the PID represents # calling process pid = 0 affinity = os.sched_getaffinity (pid) # Print result print ( "Process is eligibl to run on: " , affinity) # Change processor binding mask Caller ID process # using the os.sched_setaffin method ity () # Below the processor affinity mask will be # limit the process to only # these 2 processors (0, 1) i.e. the process can # run only on these processors affinity_mask = { 0 , 1 } pid = 0 os.sched_setaffinity ( 0 , affinity_mask) print ( "CPU affinity mask is modified for process id% s" % pid) # Now get the processor set again # on which the process is called pid = 0 affinity = os.sched_getaffinity (pid) # Print result print ( "Now, process is eligibl to run on: " , affinity) |
Exit :
Number of CPUs: 4 Process is eligibl to run on: {0, 1, 2, 3} CPU affinity mask is modified for process id 0 Now, process is eligibl to run on: {0, 1}
Links :