Python多進程共享numpy 數(shù)組的方法
為什么要用numpy
Python中提供了list容器,可以當(dāng)作數(shù)組使用。但列表中的元素可以是任何對象,因此列表中保存的是對象的指針,這樣一來,為了保存一個簡單的列表[1,2,3]。就需要三個指針和三個整數(shù)對象。對于數(shù)值運算來說,這種結(jié)構(gòu)顯然不夠高效。
Python雖然也提供了array模塊,但其只支持一維數(shù)組,不支持多維數(shù)組(在TensorFlow里面偏向于矩陣理解),也沒有各種運算函數(shù)。因而不適合數(shù)值運算。
NumPy的出現(xiàn)彌補了這些不足。
引用:https://zhuanlan.zhihu.com/p/32513483
共享 numpy 數(shù)組
需要用到 numpy 時往往是數(shù)據(jù)量較大的場景,如果直接復(fù)制會造成大量內(nèi)存浪費。共享 numpy 數(shù)組則是通過上面一節(jié)的 Array 實現(xiàn),再用 numpy.frombuffer 以及 reshape 對共享的內(nèi)存封裝成 numpy 數(shù)組,代碼如下:
# encoding:utf8 import ctypes import os import multiprocessing import numpy as np NUM_PROCESS = multiprocessing.cpu_count() def worker(index): main_nparray = np.frombuffer(shared_array_base, dtype=ctypes.c_double) main_nparray = main_nparray.reshape(NUM_PROCESS, 10) pid = os.getpid() main_nparray[index, :] = pid return pid if __name__ == "__main__": shared_array_base = multiprocessing.Array( ctypes.c_double, NUM_PROCESS * 10, lock=False) pool = multiprocessing.Pool(processes=NUM_PROCESS) result = pool.map(worker, range(NUM_PROCESS)) main_nparray = np.frombuffer(shared_array_base, dtype=ctypes.c_double) main_nparray = main_nparray.reshape(NUM_PROCESS, 10) print( main_nparray )
運行結(jié)果:
到此這篇關(guān)于Python多進程共享numpy 數(shù)組的方法的文章就介紹到這了,更多相關(guān)Python多進程共享numpy 數(shù)組內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。