Skip to main content
 首页 » 编程设计

python之控制 python 代码在不同的内核上运行

2024年10月01日10Leo_wl

我的机器上有 4 个内核的 ubuntu 操作系统。另外,我有一个名为 python.py 的 python 脚本,它具有不同的功能,例如 def1、def2 和 def 3。 我想在 core 1 上运行 def1 ,其余的在 core 2 到 4 上运行。 我知道我可以使用:

       #taskset -c 1 python.py  

这个问题使得整个脚本在其中的每个函数都在一个核心上运行。但是,我想在特定核心上运行特定功能,例如:

       def add(a,b): 
           return a+b 
 
       def sub(s, t): 
           return s-t 
 
       def mult(y,x): 
           return y*x 
 
      add(3,4)  # run this function on core 0 
      sub(3,4)  # run this function on core 1 
      mult(2,3)  # I don't core run on core 2 or 3 

我的问题是:这可能吗?

请您参考如下方法:

是的,您可以在不同的进程中运行每个函数以利用多核。这是一个例子:

from multiprocessing import Process 
 
def add(a,b): 
    return a+b 
 
def sub(s, t): 
    return s-t 
 
def mult(y,x): 
    return y*x 
 
if __name__ == "__main__": 
    # construct a different process for each function 
    processes = [Process(target=add, args=(3,4)), 
                 Process(target=sub, args=(3,4)), 
                 Process(target=mult, args=(2,3))] 
 
    # kick them off  
    for process in processes: 
        process.start() 
 
    # now wait for them to finish 
    for process in processes: 
        process.join() 

无需强制操作系统在特定内核上运行特定进程。如果您的 CPU 上有多个内核,操作系统将跨这些内核调度进程。您不太可能需要做任何类型的 CPU pinning这里。

上面的例子太简单了,看不到你的多核参与。相反,您可以尝试这个示例,它是上述示例的一个简单的 CPU 限制问题变体——即它只是一个需要更多计算的版本。

from multiprocessing import Process 
 
 
def add(a, b): 
    total = 0 
    for a1, b1 in zip(a, b): 
        total = a1 + b1 
    return total 
 
 
def sub(s, t): 
    total = 0 
    for a1, b1 in zip(s, t): 
        total = a1 - b1 
    return total 
 
 
def mult(y, x): 
    total = 0 
    for a1, b1 in zip(y, x): 
        total = a1 * b1 
    return total 
 
 
if __name__ == "__main__": 
    # construct a different process for each function 
    max_size = 1000000000 
    processes = [Process(target=add, args=(range(1, max_size), range(1, max_size))), 
                 Process(target=sub, args=(range(1, max_size), range(1, max_size))), 
                 Process(target=mult, args=(range(1, max_size), range(1, max_size)))] 
 
    # kick them off  
    for process in processes: 
        process.start() 
 
    # now wait for them to finish 
    for process in processes: 
        process.join() 

如果您查看 top 输出(并按 1 查看内核),您应该会看到类似这样的内容,其中三个内核的使用率为 100%(或接近)。这不需要进行任何 CPU 固定。更容易信任操作系统来完成并行性。