简体   繁体   English

多处理输出比单处理慢

[英]Multiprocessing output slower than single process

I'm running this code, and it seems running the script using multiprocesses is slower than running it via a single process. 我正在运行此代码,似乎使用多进程运行脚本比通过单个进程运行脚本要慢。

Am I doing something wrong? 难道我做错了什么?

from time import time
numbers = [(1963309, 2265973), (2030677, 3814172),
           (1551645, 2229620), (2039045, 2020802)]
start = time()
results = list(map(gcd, numbers))
print(results)
end = time()


print('time is %.3f'%(end - start))

from multiprocessing import Pool


if __name__ == '__main__':
    start = time()
    with Pool(4) as p:
      print(p.map(gcd, numbers))
    end = time()
    #print('time is %.3f'%(end - start))
    print('Took %.3f seconds' % (end - start))

output is 输出是

[1, 1, 5, 1]   # single process
time is 0.444
[1, 1, 5, 1]   #multi-processes
Took 0.751 seconds

Thank you. 谢谢。

It's a bad example of multiprocessing advantages. 这是多处理优势的一个不好的例子。 It obvious will be slower because you spent more time on creating and starting each process than on executing your function. 很明显,它会变慢,因为与创建函数相比,您在创建和启动每个进程上花费了更多时间。 Multiprocessing sensible in case you have really big time consuming function so you put it in separate process. 如果您真的有很多耗时的功能,那么明智的选择是多处理,因此可以将其放在单独的过程中。

Your timing is unfair. 您的时间安排不公平。 list(map(gcd, numbers)) is an in-process operation and doesn't start a new process. list(map(gcd, numbers))是一个进程内操作,不会启动新进程。

The Pool class represents a pool of worker processes. Pool类表示辅助进程池。

Starting a new process is intuitively slower than simply executing list(map(gcd, numbers)) , relative to list(map(...)) there's so much going on in Pool to start the processes. 从直观list(map(gcd, numbers))开始新流程要比简单地执行list(map(gcd, numbers))慢,相对于list(map(...)) ,在Pool有太多事情可以启动流程。 It's almost like comparing the speed of elephants and cheetahs. 这几乎就像比较大象和猎豹的速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM