Python并行计算简单实现

Python并行计算简单实现

multiprocessing包是Python中的多进程管理包.
Pool(num)类提供一个进程池,然后在多个核中执行这些进程,
其中默认参数num是当前机器CPU的核数.

Pool.map(func, iterable[, chunksize=None])
2个参数, 第一个参数是函数, 第二个参数是需要可迭代的变量, 作为参数传递到func

如果func含有的参数多于一个,可以利用functools.partial 先处理.
以下是一个简单的例子.

from multiprocessing import Pool
from functools import partial 

def somefunc(str_1, str_2, iterable_iterm):
    print("%s %s %d" % (str_1, str_2, iterable_iterm))

def main():
    iterable = [1, 2, 3, 4, 5]
    pool = Pool()
    str_1 = "This"
    str_2 = "is"
    func = partial(somefunc, str_1, str_2)
    pool.map(func, iterable)
    pool.close()
    pool.join()

if __name__ == "__main__":
    main()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值