我试图找到一种更快的方式来运行numpy / sklearn来对数据列表执行某些任务。我有一些书建议我在重数据计算工作中使用Process而不是Thread。在执行此操作时,我发现线程运行速度比Process快。这是为什么?我应该选择哪种方式?
# -*- 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)
使用python 3.6在Win7-4 Real Core-I5-4700上运行。这是输出:
方式| Workerjob | Process Num在taskmgr中显示|工作时加载Cpu |时间成本
2threads | numpy | 1 process | 100%| 9s
2threads | sklearn | 1个过程| 100%| 35s
2 process | numpy | 3 process | 100%| 36s
2 process | sklearn | 3 process | 100%| 77s
为什么流程花费更多时间?如何找到更好的方法来降低时间成本并充分利用多核OS?
好。我有它。对于那些可以像numpy一样释放GIL的模块,使用线程后端将通过减少从主进程到子进程的Np对象复制成本来节省时间。