我正在Windows 10(Intel Core i7-8550U处理器)上尝试使用Python 3.7.4进行python多处理。
我正在用两个函数测试多重处理,一个函数使用基本sleep(),另一个函数使用sklearn的matthews_corrcoef。多重处理可使用睡眠功能,但不能使用sklearn功能。
import numpy as np
from sklearn.metrics import matthews_corrcoef
import time
import concurrent.futures
from multiprocessing import Process,Pool
from functools import partial
import warnings
import sys
class Runner():
def sleeper(self,pred,man,thr = None):
return time.sleep(2)
def mcc_score(self,thr = None):
warnings.filterwarnings("ignore")
return matthews_corrcoef(pred,man)
def pool(self,func):
t1 = time.perf_counter()
p = Pool()
meth = partial(func,man)
res = p.map(meth,thres)
p.close()
t2 = time.perf_counter()
print(f'Pool {func.__name__} {round((t2-t1),3)} seconds')
def vanilla(self,func):
t1 = time.perf_counter()
for t in thres:
func(pred,man)
t2 = time.perf_counter()
print(f'vanilla {func.__name__} {round((t2-t1),3)} seconds')
if __name__== "__main__":
print(sys.version)
r = Runner()
thres = np.arange(0,1,0.3)
print(f"Number of thresholds {len(thres)}")
pred = [1]*200000
man = [1]*200000
results = []
r.pool(r.mcc_score)
r.vanilla(r.mcc_score)
r.pool(r.sleeper)
r.vanilla(r.sleeper)
在Windows中,对于mcc_score函数,使用pool实际上比普通版本慢,而在Linux中,它可以正常工作。
这是示例输出
#windows
3.7.4 (default,Aug 9 2019,18:34:13) [MSC v.1915 64 bit (AMD64)]
Number of thresholds 4
Pool mcc_score 3.247 seconds
vanilla mcc_score 1.591 seconds
Pool sleeper 5.828 seconds
vanilla sleeper 8.001 seconds
#linux
3.7.0 (default,Jun 28 2018,13:15:42) [GCC 7.2.0]
Number of thresholds 34
Pool mcc_score 1.946 seconds
vanilla mcc_score 8.817 seconds
我遍历了stackoverflow中的文档和其他相关问题,其中主要指出使用if __name__== "__main__":
。非常感谢您的帮助,因为我已经坚持了很长时间。如果我错过任何重要信息,请提及,我会提供。