我正在尝试找到一种更快的方法来运行numpy/sklearn来对数据列表执行一些任务。我有一些书建议我在繁重的数据计算工作中使用Process而不是Thread。在这样做的时候,我发现线程的运行速度比进程快。为什么会这样呢?我应该选择哪种方式?
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 2 10:20:19 2019
@author: Simon
"""
import time
import numpy as np
from sklearn import linear_model
from concurrent.futures import ProcessPoolExecutor as Pool
from concurrent.futures import ThreadPoolExecutor as Pool
xx, yy = np.meshgrid(np.linspace(0,10,1000), np.linspace(10,100,1000))
zz = 1.0 * xx + 3.5 * yy + np.random.randint(0,100,(1000,1000))
X, Z = np.column_stack((xx.flatten(),yy.flatten())), zz.flatten()
regr = linear_model.LinearRegression()
def regwork(t):
X=t[0]
Z=t[1]
regr.fit(X, Z)
a, b = regr.coef_, regr.intercept_
return a
def numpywork(t):
X=t[0]
Z=t[1]
for i in range(1):
r=np.sum(X,axis=1)+np.log(Z)
return np.sum(r)
if __name__=="__main__":
r=regx((X,Z))
rlist=[[X,Z]]*500
start=time.clock()
pool = Pool(max_workers=2)
results = pool.map(numpywork, rlist)
for ret in results:
print(ret)
print(time.clock()-start)在Win7-4 Real Core-I5-4700和python 3.6上运行。下面是输出:
Ways|Workerjob|taskmgr显示的进程数|工作时的Cpu负载|时间开销
2thread|numpy |1进程|100%|9s
2threads|sklearn|1进程|100%|35s
2process|numpy |3进程|100%|36s
2process|sklearn|3进程|100%|77s
为什么流程要花费更多的时间?如何找到一种更好的方法来降低时间成本,充分利用多核操作系统?
发布于 2019-04-12 10:39:27
好的。我知道了。对于那些可以发布像numpy这样的GIL的模块,使用线程后端将通过减少从主进程到子进程的Np对象复制成本来节省时间。
https://stackoverflow.com/questions/55474552
复制相似问题