Python多进程多线程耗时对比

python多进程多线程耗时对比

import multiprocessing as mp
import threading as td
import time

def job(q):
    res=0
    for i in range(10000000):
        res+= i+i**2+i**3
    q.put(res)

def normal():
    res = 0
    for _ in range(2):
        for i in range(10000000):
            res += i + i**2 + i**3
    print('normal:', res)
    
def multicore():
    q = mp.Queue()
    p1 = mp.Process(target = job, args=(q,))
    p2 = mp.Process(target=job, args=(q,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    res1=q.get()
    res2=q.get()
    print('multicore:',res1+res2)
    
def multithread():
    q = mp.Queue()
    t1 = td.Thread(target = job, args=(q,))
    t2 = td.Thread(target=job, args=(q,))
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    res1=q.get()
    res2=q.get()
    print('multithread:',res1+res2)


if __name__=='__main__':
    st = time.time()
    normal()
    st1 = time.time()
    print('normal time:', st1 - st)
    multithread()
    st2 = time.time()
    print('multithread time:', st2 - st1)
    multicore()
    print('multicore time:', time.time() - st2)

#range(100000)
normal: 499999666667166666000000
normal time: 1.8084125518798828
multithread: 499999666667166666000000
multithread time: 2.0068132877349854
multicore: 499999666667166666000000
multicore time: 1.1333837509155273

#range(1000000)
normal: 4999999666666716666660000000
normal time: 18.83209800720215
multithread: 4999999666666716666660000000
multithread time: 50.44354844093323
multicore: 4999999666666716666660000000
multicore time: 9.9707932472229

你可能感兴趣的:(python)