python--并发编程 07 进程池/线程池对比

思考:concurrent.futures有进程池ProcessPoolExecutor和线程池ThreadPoolExecutor ,multiprocessing有进程池Pool,他们的运行效率如何?

导入方法:

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
from multiprocessing import Pool

concurrent.futures是异步调用机制

执行效率

ThreadPoolExecutor 执行效率

程序:

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
from multiprocessing import Pool
import time

# 计算平方求和
def func(n):
    sum = 0
    for i in range(n):
        sum += n ** 2
    print(sum)



if __name__ == '__main__':

    # 执行时间大概0.19s
    tp = ThreadPoolExecutor(20)     # 调用线程池求和
    start_time = time.time()
    for i in range(1000):
        tp.submit(func, i)
    tp.shutdown()    #等效于pool中的close+join
    print('ThreadPoolExecutor线程池计算消耗的时间是:%s' % (time.time()-start_time))

 

ProcessPoolExecutor执行效率

程序:

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
from multiprocessing import Pool
import time

# 计算平方求和
def func(n):
    sum = 0
    for i in range(n):
        sum += n ** 2
    print(sum)



if __name__ == '__main__':

    # 执行时间大概1.65s
    pp = ProcessPoolExecutor(20)     # 调用进程池求和
    start_time = time.time()
    for i in range(1000):
        pp.submit(func, i)
    pp.shutdown()    #等效于pool中的close+join
    print('ProcessPoolExecutor进程池计算消耗的时间是:%s' % (time.time()-start_time))

 

Pool执行效率

程序:

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
from multiprocessing import Pool
import time

# 计算平方求和
def func(n):
    sum = 0
    for i in range(n):
        sum += n ** 2
    print(sum)



if __name__ == '__main__':
# 执行时间大概0.30
    po = Pool(5)
    start_time = time.time()
    for i in range(1000):
        po.apply_async(func, args=(i, ))
    po.close()
    po.join()
    print('pool进程池计算消耗时间是:%s' % (time.time()-start_time))

 

对比总结

上面的程序是计算任务,从运行结果看concurrent.futures的ProcessPoolExecutor进程池和multiprocessing的进程池Pool运行效率相差不大。都比线程池ThreadPoolExecutor 大很多。

因此,偏计算的任务使用进程池的效率明显高于线程池。即密集型计算使用进程池,密集型IO使用线程池。

 

回调函数被谁调用

线程池中的回调函数是子线程调用的,和父线程无关。

进程池中的回调函数是父进程调用的,和子进程无关。

你可能感兴趣的:(#,04python并发编程)