【发布时间】:2020-03-01 04:22:40
【问题描述】:
我正在尝试在 Windows 10、Intel Core i7-8550U 处理器上使用 Python 3.7.4 进行 python 多处理。
我正在使用两个函数测试多处理,一个是基本的 sleep(),另一个是使用 sklearn 的 matthews_corrcoef。多处理适用于 sleep 函数,但不适用于 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, pred, man, thr = None):
warnings.filterwarnings("ignore")
return matthews_corrcoef(pred, man)
def pool(self, func):
t1 = time.perf_counter()
p = Pool()
meth = partial(func, pred, 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 实际上比 vanilla 版本慢,而在 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__": 进行说明。一些帮助将不胜感激,因为我已经坚持了很长一段时间了。如果我遗漏了任何重要信息,请指出,我会提供。
【问题讨论】:
-
是否有可能 numpy 已经在后台进行多线程处理?尝试根据这个问题禁用它:stackoverflow.com/questions/17053671/…
标签: python windows scikit-learn python-multiprocessing python-pool