numpy 在多个内核上运行Python脚本

cfh9epnr  于 2023-06-23  发布在  Python
关注(0)|答案(2)|浏览(126)

我有12个Python脚本。我尝试在核心1上运行脚本1-3,在核心2上运行脚本4-6,在核心3上运行脚本7-9,在核心4上运行脚本10-12,但无法保存数据。我的笔记本电脑有4个逻辑核心。我在下面介绍代码。

import multiprocessing
import os

def run_script(script_number):
    # Define the CPU core affinity for each script
    cpu_affinities = {
        1: [0],
        2: [1],
        3: [2],
        4: [3],
    }

    # Set the CPU affinity for the current process
    os.sched_setaffinity(0, cpu_affinities[script_number])

    # Execute the script
    script_file = f"script_{script_number}.py"
    os.system(f"python {script_file}")

if __name__ == '__main__':
    # Create a multiprocessing pool with 4 processes
    pool = multiprocessing.Pool(processes=4)

    # Submit the scripts to the pool
    for script_number in range(1, 13):
        pool.apply_async(run_script, args=(script_number,))

    # Close the pool and wait for all processes to complete
    pool.close()
    pool.join()

脚本1-12

import numpy as np
def fibonacci(n):
    sequence = [0, 1]
    while len(sequence) < n:  
        next_number = sequence[-1] + sequence[-2]  
        sequence.append(next_number)  
    return sequence

n = 3
for i in range(0,n): 
    result = fibonacci(i)
    print(result)
    
    with open("1.txt", 'a') as f: #the file number will change accordingly
        f.writelines('\n') 
        f.write(str(result))
    print(result)
tpxzln5u

tpxzln5u1#

如果你只是想把你的脚本分布在一些内核上,你应该使用gnu parallel。不需要使用python脚本,它负责将Fibonacci脚本分配给某些核心。命令行中的命令如下:
parallel --jobs 4 python fibonacci.py {1} ::: 1.txt 2.txt 3.txt ... 12.txt
请注意,此解决方案要求Fibonacci脚本接受一个命令行参数。要处理命令行输入,可以使用 argparse 库。

7fyelxc5

7fyelxc52#

您对如何将内核分配给脚本的口头描述与实际代码并不完全匹配。但我会按照你的口头描述去做:您正在按顺序将数字1到12添加到池的输入任务队列中。任务将由池进程按照队列中的顺序执行。因此,要执行的前4个脚本将是1到4。然而,您说您希望脚本1到3在同一个核心上运行。您刚刚限制了前4个脚本在核心1和2上执行。这显然不是最佳并行。
首先,我不知道你为什么关心脚本运行在什么内核上。限制脚本在特定核心上运行可能会影响性能。也就是说,我假设您决定在哪个内核上运行脚本有点武断,并且正如我所说的,这并不是最好的分配。因此,我们只是确保每个池进程都被限制在单个核心中,而不是真正关心哪个池进程执行哪个脚本。”””这对你工作吗?**通过这种方式,我们仍然可以确保当4个脚本并行执行时,每个脚本都被限制在自己的不同核心中执行。如果这对您有用,那么我建议您不要使用os.system调用创建一个新进程来执行12个脚本中的每一个,为什么不直接导入脚本呢?

import multiprocessing
import os
from importlib import import_module

def init_pool_processes(core_number):
    with core_number.get_lock():
        core = core_number.value
        core_number.value += 1
    os.sched_setaffinity(0, [core])

def run_script(script_number):
    # Execute the script
    import_module(f"script_{script_number}")

if __name__ == '__main__':
    # Create a multiprocessing pool with 4 processes
    # assigning to each process its own CPU affinity:
    core_number = multiprocessing.Value('i', 1)
    pool = multiprocessing.Pool(processes=4, initializer=init_pool_processes, initargs=(core_number,))

    # Submit the scripts to the pool
    pool.map(run_script, range(1, 13))

    # Close the pool and wait for all processes to complete
    pool.close()
    pool.join()

相关问题