用进程池的多进程和单进程分别运行查看结果

时间single 0.09075808525085449 multi 4.713615894317627。因此计算量不是特别大不建议使用多进程。
import threading
import time
ind=100

def single():
    for j in range(ind):
        for i in range(5000):
            w=2*i
            #print(w)
    return '123'
def s(w):
    for i in range(5000):
        w=2*i
        #print(w)
    return '123'
def multi():
    threa=[]
    for j in range(ind):
        t=threading.Thread(target=s)

        threa.append(t)
    for t in threa:
        t.start()
    for t in threa:
        t.join()
from concurrent.futures import ProcessPoolExecutor
if __name__ == '__main__':
    dan_sum=0
    multi_sum=0
    start=time.time()
    single()
    end=time.time()
    sum=0
    sum1=0
    sum=end-start
    start=time.time()
    with ProcessPoolExecutor() as pool:
        results=pool.map(s,[i for i in range(ind)])
    end=time.time()
    sum1=end-start
    for i in results:
        print(i)
    print('single',sum,'multi',sum1,dan_sum,multi_sum)
posted @ 2023-05-03 16:09  祥瑞哈哈哈  阅读(16)  评论(0编辑  收藏  举报