Python 创建和填充巨大numpy 2D阵列的最快方法?
我必须创建一个巨大的数组(例如,96go,72000行*72000列),并在每种情况下使用来自数学公式的浮点数进行填充。之后将计算数组Python 创建和填充巨大numpy 2D阵列的最快方法?,python,matrix,numpy,multiprocessing,multidimensional-array,Python,Matrix,Numpy,Multiprocessing,Multidimensional Array,我必须创建一个巨大的数组(例如,96go,72000行*72000列),并在每种情况下使用来自数学公式的浮点数进行填充。之后将计算数组 import itertools, operator, time, copy, os, sys import numpy from multiprocessing import Pool def f2(x): # more complex mathematical formulas that change according to values in *
import itertools, operator, time, copy, os, sys
import numpy
from multiprocessing import Pool
def f2(x): # more complex mathematical formulas that change according to values in *i* and *x*
temp=[]
for i in combine:
temp.append(0.2*x[1]*i[1]/64.23)
return temp
def combinations_with_replacement_counts(n, r): #provide all combinations of r balls in n boxes
size = n + r - 1
for indices in itertools.combinations(range(size), n-1):
starts = [0] + [index+1 for index in indices]
stops = indices + (size,)
yield tuple(map(operator.sub, stops, starts))
global combine
combine = list(combinations_with_replacement_counts(3, 60)) #here putted 60 but need 350 instead
print len(combine)
if __name__ == '__main__':
t1=time.time()
pool = Pool() # start worker processes
results = [pool.apply_async(f2, (x,)) for x in combine]
roots = [r.get() for r in results]
print roots [0:3]
pool.close()
pool.join()
print time.time()-t1
- 创建和填充如此巨大的numpy阵列的最快方法是什么?填满 列表然后聚合然后转换为numpy数组李>
- 我们是否可以在知道 2d阵列是否独立,以加快阵列填充速度?使用多处理优化此类计算的线索/线索
多处理.Pool
填充其值。正确地执行此操作还可以使池中每个进程的内存占用相对较小。我知道您可以创建共享numpy阵列,这些阵列可以从不同的线程进行更改(假设更改的区域不重叠)。下面是您可以使用的代码草图(我在stackoverflow的某个地方看到了最初的想法,编辑:在这里)
它需要实时还是可以离线计算并使用pickle读取?我更喜欢实时,但如果pickle更快,我不介意…希望我能很好地理解你的问题?看,所以我不这么认为works@sega_sai有趣。我不会删除我的答案,因为我相信其他人(像我一样)可以从看到它以及你的评论中吸取教训。谢谢,行吗?我不明白单身班的兴趣/诀窍。我有TypeError:“非类型”对象不支持项分配。我试过修改,但没有结果。你能再帮我一点吗?我的代码在linux上运行(已验证)。如果你有窗户的话,恐怕你会有不同的做法。(因为进程不会从池中继承singleton.arr值)。
import multiprocessing as mp ,numpy as np, ctypes
def shared_zeros(n1, n2):
# create a 2D numpy array which can be then changed in different threads
shared_array_base = mp.Array(ctypes.c_double, n1 * n2)
shared_array = np.ctypeslib.as_array(shared_array_base.get_obj())
shared_array = shared_array.reshape(n1, n2)
return shared_array
class singleton:
arr = None
def dosomething(i):
# do something with singleton.arr
singleton.arr[i,:] = i
return i
def main():
singleton.arr=shared_zeros(1000,1000)
pool = mp.Pool(16)
pool.map(dosomething, range(1000))
if __name__=='__main__':
main()