Python中的OS模塊提供了與操作係統進行交互的函數。操作係統屬於Python的標準實用程序模塊。該模塊提供了使用依賴於操作係統的函數的便攜式方法。
os.sched_setaffinity()
Python中的方法用於設置由指定進程ID指示的進程的CPU親和力掩碼。進程的CPU相似性掩碼確定了可以運行的CPU組。
注意:此方法僅在某些UNIX平台上可用。
用法: os.sched_setaffinity(pid, mask)
參數:
pid:需要設置其CPU關聯掩碼的進程的進程ID。 Process的CPU親和力掩碼決定了可以在其上運行的CPU組。
pid為0表示調用過程。
mask:一個整數的整數,表示應將進程限製在其中的CPU集合。
返回類型:此方法不返回任何值。
代碼:os.sched_setaffinity()方法的使用
# Python program to explain os.sched_setaffinity() method
# importing os module
import os
# Get the number of CPUs
# in the system
# using os.cpu_count() method
print("Number of CPUs:", os.cpu_count())
# Get the set of CPUs
# on which the calling process
# is eligible to run. using
# os.sched_getaffinity() method
# 0 as PID represnts the
# calling process
pid = 0
affinity = os.sched_getaffinity(pid)
# Print the result
print("Process is eligibl to run on:", affinity)
# Change the CPU affinity mask
# of the calling process
# using os.sched_setaffinity() method
# Below CPU affinity mask will
# restrict a process to only
# these 2 CPUs (0, 1) i.e process can
# run on these CPUs only
affinity_mask = {0, 1}
pid = 0
os.sched_setaffinity(0, affinity_mask)
print("CPU affinity mask is modified for process id % s" % pid)
# Now again, Get the set of CPUs
# on which the calling process
# is eligible to run.
pid = 0
affinity = os.sched_getaffinity(pid)
# Print the result
print("Now, process is eligibl to run on:", affinity)
輸出:
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}
參考文獻:
- https://docs.python.org/3/library/os.html#os.sched_setaffinity
- https://linux.die.net/man/2/sched_getaffinity
相關用法
- Python next()用法及代碼示例
- Python os.dup()用法及代碼示例
- Python set()用法及代碼示例
- Python Decimal max()用法及代碼示例
- Python PIL ImageOps.fit()用法及代碼示例
- Python os.rmdir()用法及代碼示例
- Python sympy.det()用法及代碼示例
- Python Decimal min()用法及代碼示例
- Python os.readlink()用法及代碼示例
- Python os.writev()用法及代碼示例
- Python os.readv()用法及代碼示例
- Python PIL RankFilter()用法及代碼示例
- Python os.rename()用法及代碼示例
- Python os.sendfile()用法及代碼示例
注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | os.sched_setaffinity() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。