最近打比赛,apply操作极慢,队友使用了线程池,用多核开辟多线程跑,加速。
在阿里平台上,都没问题。
我是win10系统+jupyter notebook
多线程那个模块运行,会显示一直运行,p.close()会被卡死
from multiprocessing importPooldefdf_cut_word(data, c):
data[c]= data[c].map(lambda x: ' '.join(jieba.cut(x)))returndata[[c]]
processor= 12list_seg= ["prefix", "title", "text0", "text1", "text2", "text3", "text4", "text5", "text6", "text7", "text8","text9"]
cut_word_args=list_seg
p=Pool(processor)
res=[]for i inrange(len(cut_word_args)):print(cut_word_args[i])
res.append(
p.apply_async(df_cut_word, args=(
data[[cut_word_args[i]]], cut_word_args[i]))
)print(str(i) + 'processor started !')
p.close()
p.join()
res= [item.get() for item inres]
res= pd.concat(res, axis=1)print(res.columns)
data= data[[c for c in data.columns if c not inres.columns]]
data= pd.concat([data, res], axis=1)
这是linux的写法
在Windows上要想使用进程模块,就必须把有关进程的代码写在当前.py文件的if __name__ == ‘__main__’ :语句的下面,才能正常使用Windows下的进程模块。Unix/Linux下则不需要。
改为:
from multiprocessing importPooldefdf_cut_word(data, c):
data[c]= data[c].map(lambda x: ' '.join(jieba.cut(x)))returndata[[c]]
list_seg= ["prefix", "title", "text0", "text1", "text2", "text3", "text4", "text5", "text6", "text7", "text8","text9"]if __name__=='__main__':
processor= 2cut_word_args=list_seg
p=Pool(processor)
res=[]for i inrange(len(cut_word_args)):print(cut_word_args[i])
res.append(
p.apply_async(df_cut_word, args=(
data[[cut_word_args[i]]], cut_word_args[i]))
)print(str(i) + 'processor started !')print('ok')
p.close()
p.join()
然而还是不行,后来搜到了
在Windows环境中,jupyter-notebook中,即使使用if __name__ == '__main__进行保护,也会出现runtime error,这个时候可以将jupyter中的代码下载成py脚本,直接运行脚本。
作为对比,Linux下运行的jupyter-notebook并不会。