假设我有一个大内存numpy数组,我有一个函数func,它接受这个巨大的数组作为输入(连同一些其他参数).func具有不同参数可以并行运行.例如:
def func(arr, param):
# do stuff to arr, param
# build array arr
pool = Pool(processes = 6)
results = [pool.apply_async(func, [arr, param]) for param in all_params]
output = [res.get() for res in results]
Run Code Online (Sandbox Code Playgroud)
如果我使用多处理库,那么这个巨型数组将被多次复制到不同的进程中.
有没有办法让不同的进程共享同一个数组?此数组对象是只读的,永远不会被修改.
更复杂的是,如果arr不是一个数组,而是一个任意的python对象,有没有办法分享它?
[EDITED]
我读了答案,但我仍然有点困惑.由于fork()是copy-on-write,因此在python多处理库中生成新进程时不应调用任何额外的成本.但是下面的代码表明存在巨大的开销:
from multiprocessing import Pool, Manager
import numpy as np;
import time
def f(arr):
return len(arr)
t = time.time()
arr = np.arange(10000000)
print "construct array = ", time.time() - t;
pool = Pool(processes = 6)
t = …Run Code Online (Sandbox Code Playgroud) python parallel-processing numpy shared-memory multiprocessing
我遇到了一个我似乎无法理解的记忆问题.
我在Windows 7 64位机器上运行8GB内存并运行32位python程序.
这些程序读取了5,118个压缩的numpy文件(npz).Windows报告磁盘上的文件占用1.98 GB
每个npz文件包含两个数据:'arr_0'的类型为np.float32,'arr_1'的类型为np.uint8
python脚本读取每个文件将其数据附加到两个列表中,然后关闭该文件.
在文件4284/5118周围,程序抛出一个MemoryException
但是,任务管理器说发生错误时python.exe*32的内存使用量是1,854,848K~ = 1.8GB.远低于我的8 GB限制,或者假定的32位程序的4GB限制.
在程序中我捕获内存错误并报告:每个列表的长度为4285.第一个列表包含总共1,928,588,480个float32的〜= 229.9 MB的数据.第二个列表包含12,342,966,272 uint8的〜= 1,471.3MB数据.
所以,一切似乎都在检查.除了我得到内存错误的部分.我绝对有更多的内存,它崩溃的文件大约是800KB,因此读取一个巨大的文件并没有失败.
此外,该文件未损坏.如果我事先没有耗尽所有的记忆,我可以读得很好.
为了让事情变得更加混乱,所有这一切似乎在我的Linux机器上运行良好(虽然它确实有16GB的内存,而不是我的Windows机器上的8GB),但是,它似乎并不是机器的RAM.造成这个问题.
为什么Python会抛出内存错误,当我预计它应该能够分配另外2GB的数据?
我有这个简单的函数,它分区列表并返回列表中的索引i,使索引小于i的元素小于list [i],索引大于i的元素更大.
def partition(arr):
first_high = 0
pivot = len(arr) - 1
for i in range(len(arr)):
if arr[i] < arr[pivot]:
arr[first_high], arr[i] = arr[i], arr[first_high]
first_high = first_high + 1
arr[first_high], arr[pivot] = arr[pivot], arr[first_high]
return first_high
if __name__ == "__main__":
arr = [1, 5, 4, 6, 0, 3]
pivot = partition(arr)
print(pivot)
Run Code Online (Sandbox Code Playgroud)
OS X上的python 2.7.6的python 3.4运行时间要大得多:
time python3 partition.py
real 0m0.040s
user 0m0.027s
sys 0m0.010s
time python partition.py
real 0m0.031s
user 0m0.018s
sys 0m0.011s
Run Code Online (Sandbox Code Playgroud)
在ubuntu 14.04 /虚拟机上也是如此
python3:
real …Run Code Online (Sandbox Code Playgroud) python ×3
numpy ×2
file-io ×1
generator ×1
memory ×1
performance ×1
python-2.7 ×1
python-3.x ×1
windows ×1