系统相关
首页 > 系统相关> > python之多进程multiprocessing

python之多进程multiprocessing

作者:互联网

做实验对比不同算法效果的时候,需要得到多个算法的解,如果按单线程依次运行,速度过慢,特别对于需要实验多次,比较均值和方差的时候,时间消耗更大,这时候最好使用多进程的方法,来节省时间。下面是做实验时运用的线程池的代码:

import multiprocessing as mp
def worker_1():
    algorithm1.run(9200)
    solutions1 = algorithm1.result
    return solutions1

def worker_2():
    algorithm2.run(10000) 
    solutions2 = algorithm2.result
    return solutions2

def worker_3():
    algorithm3.run(10000) 
    solutions3 = algorithm3.result
    return solutions3
def worker_4():
    algorithm4.run(9200)  
    solutions4 = algorithm4.result
    return solutions4
def worker_5():
    algorithm5.run(10000)  
    solutions5 = algorithm5.result
    return solutions5

def worker_6():
    algorithm6.run(10000)  
    solutions6= algorithm6.result
    return solutions6
fun_list = [worker_1,worker_2,worker_3,worker_4,worker_5,worker_6]

def multicore():
    pool=mp.Pool(processes=2)#定义一个Pool,并定义CPU核数量为2
    multi_res = []
    for fun in fun_list:
        res=pool.apply_async(fun)
        multi_res.append(res)
    results_t = [res.get()for res in multi_res]
    solutions1 = results_t[0]
    solutions2 = results_t[1]
    solutions3 = results_t[2]
    solutions4 = results_t[3]
    solutions5 = results_t[4]
    solutions6 = results_t[5]
    return solutions1,solutions2,solutions3,solutions4,solutions5,solutions6
if __name__=='__main__':
    solutions1, solutions2, solutions3, solutions4, solutions5, solutions6 = multicore()

标签:return,python,res,worker,results,result,之多,multiprocessing,def
来源: https://blog.csdn.net/qq_38384924/article/details/88651342