for 循环, 多进程并行加速

##########  for 循环并行,单一参数 #############
import time
import multiprocessing


def do(i):
    print(i)
    time.sleep(2)

if __name__ == '__main__':

    param = []
    #假设有100次循环
    for i in range(0, 100):
        param.append(i)

    p = multiprocessing.Pool(4)

    p.map(do, param)
    p.close()
    p.join()




##########  for 循环并行,多参数 #############
import time
import multiprocessing
from functools import  partial

def do(i,a,b,c,d):
    print(i)
    time.sleep(0.02)
    print(a,b,c,d)
    time.sleep(2)

if __name__ == '__main__':

    param = []
    #假设有100次循环
    for i in range(0, 100):
        param.append(i)

    p = multiprocessing.Pool(4)
    a=0
    b=0
    c=0
    d = 0
    #partial偏函数,为do函数传入第一个参数i,其他关键字参数一一对应
    p.map(partial(do,a=a,b=b,c=c,d=d), param)
    p.close()
    p.join()

你可能感兴趣的:(IT,python,for循环,并行,map())