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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值