利用Numpy Python的多处理工具
利用Numpy Python的多处理工具
我正在尝试使用numpy数组来利用多处理工具。我想同时运行func1()
和func2()
,然后使用np.concatenate()
将Solution_1
和Solution_2
放在一起。我该如何做到这一点?
模块:
import multiprocessing import numpy as np
代码:
Numbers = np.array([1,2,3,4,5,6,7,8,9,10,11,12]) def func1(): Solution_1 = Numbers + 10 return Solution_1 def func2(): Solution_2 = Numbers * 10 return Solution_2 # 设置多处理变量 p1 = multiprocessing.Process(target=func1) p2 = multiprocessing.Process(target=func2) # 运行多进程 if __name__ == "__main__": p1.start() p2.start()
在上面的代码中,出现了以下问题:
问题1:AttributeError: 'dict' object has no attribute 'append'
原因:solutions被定义为字典而不是列表,所以无法使用append方法。
解决方法:将solutions定义为列表,即将solutions = {}改为solutions = []。
问题2:代码运行时间过长,没有停止
原因:可能与机器的核心数量有关。
解决方法:尝试调整pool = mp.Pool(num_cores-1)
,通过减少核心数量来提高运行速度。
根据类似的问题,还可以使用以下替代方法:
- 使用全局变量
- 使用apply_async
方法
- 使用共享变量进行通信
- 使用multiprocessing.Manager()
如果仍然遇到问题,可以通过上传问题的快照来进行进一步的分析。
下面是修复后的代码:
import multiprocessing as mp import numpy as np num_cores = mp.cpu_count() Numbers = np.array([1,2,3,4,5,6,7,8,9,10,11,12]) def func1(): Solution_1 = Numbers + 10 return Solution_1 def func2(): Solution_2 = Numbers * 10 return Solution_2 # Getting ready my cores, I left one aside pool = mp.Pool(num_cores-1) # This is to use all functions easily functions = [func1, func2] # This is to store the results solutions = [] for function in functions: solutions.append(pool.apply(function, ())) solutions = pd.DataFrame(solutions) print(solutions)
以上是关于使用Numpy和Python的多处理工具的问题和解决方法的整理。