从https://www.cnblogs.com/devilmaycry812839668/p/17066212.html中知道如何对python进程设置CPU绑定,本文对此进行一些延伸,给出一些例子:
代码1:
import os
from multiprocessing import Process
import time
cpu_avia = os.sched_getaffinity(os.getpid())
os.sched_setaffinity(os.getpid(), list(cpu_avia)[:2]) # 绑定两个核心
def func():
while True:
pass
process = [Process(target=func) for i in range(2)]
for proc in process:
proc.start()
time.sleep(600)
可以看到在父进程中设置绑定两个CPU,那么另个子进程每个的单CPU利用率均可以达到100% 。
现在的疑问是这个绑定2个CPU后子进程和父进程是不是一同绑在了这2个CPU上,如果父进程也进行死循环运行那么每个进程的利益率会是多少,因此给出第二个代码:
代码2:
import os
from multiprocessing import Process
cpu_avia = os.sched_getaffinity(os.getpid())
print(cpu_avia)
os.sched_setaffinity(os.getpid(), list(cpu_avia)[:2]) # 绑定两个核心
def func():
while True:
pass
process = [Process(target=func) for i in range(2)]
for proc in process:
proc.start()
func()
可以看到父进程和两个子进程的利用率总和约为200%,也就是说父进程和两个子进程被绑定到这两个CPU上,因此三个进程的CPU利用率总和为200%。
通过上面的两个例子我们知道在父进程中绑定多个CPU其实还不能很好的对子进程的CPU绑定起到细粒度的控制,为此我们给出更细粒度的绑定的例子:
代码3:
import os
from multiprocessing import Process
cpu_avia = os.sched_getaffinity(os.getpid())
print(cpu_avia)
os.sched_setaffinity(os.getpid(), list(cpu_avia)[:2]) # 绑定两个核心
def func(id):
os.sched_setaffinity(os.getpid(), list(cpu_avia)[id:id+1]) # 绑定两个核心
while True:
pass
process = [Process(target=func, args=(i+1, )) for i in range(2)]
for proc in process:
proc.start()
func(0)
===================================
参考:
https://www.cnblogs.com/devilmaycry812839668/p/17066212.html
https://blog.csdn.net/weixin_39755712/article/details/111434443
标签:avia,python,Demo,绑定,cpu,进程,os,CPU From: https://www.cnblogs.com/devilmaycry812839668/p/17066246.html