python - 并行处理比串行处理花费更长的时间并跳过处理少量条目
问题描述
为什么并行处理比 Python 中的串行处理慢?
#!/usr/bin/env python3
import os
import time
from functools import partial
import multiprocessing as mp
def print_hello(i, typ):
print(typ + " : PID-" + str(os.getpid()) + "\n")
# print("Hello World " + str(i))
if __name__ == '__main__':
N= mp.cpu_count()
parallel_start_time = time.time()
with mp.Pool(processes = N) as p:
p.map(partial(print_hello,typ="Parallel"), (x for x in range(100)))
parallel_end_time = time.time()
serial_start_time = time.time()
for x in range(100):
print_hello(x, "Serial")
serial_end_time = time.time()
print("Parallel processing took " + str(parallel_end_time - parallel_start_time) + " seconds")
print("Serial processing took " + str(serial_end_time - serial_start_time) + " seconds")
我将上述脚本的输出写入文本文件,下面是最终输出
./test_parallel.py > pid.txt
61 Parallel : PID-28311 Parallel processing took 0.11675715446472168 seconds 100 Serial : PID-28310 Serial processing took 0.0001430511474609375 seconds
我也不明白为什么python在使用并行处理时没有处理39个id
解决方案
在多处理中,您还需要考虑创建进程的开销。在此示例中,每个进程都在执行一项非常小的任务,即打印一条语句。因此,开销将非常大,这就是您获得此类结果的原因。
在CPU 密集型(计算繁重)任务中建议使用多处理。但是,这里不是这样。因此,您应该在其他示例中尝试一下。
推荐阅读
- xml - 以下哪个或哪个陈述在 XML 中是正确的?
- reactjs - 无法在 React 中显示图像,尽管它已导入文件夹中
- typo3 - 带有扩展名“extension_builder”的 TYPO3 错误 ExtensionValidator 不存在。反射失败
- css - 如何在移动浏览器底部放置固定的背景图像*总是*?(CSS)
- django - windows机器上Apache2.4的Forbidden(403)权限访问错误
- c++ - 在 C++ 中的类模板中是否可以有一个通用的、非专用的静态成员?
- javascript - Angular 我如何用异步和承诺初始化和填充数组
- amazon-web-services - 调用 AssumeRole 操作时发生错误 (AccessDenied)
- python - x轴的seaborn matplotlib包装不起作用
- google-maps-api-3 - 如何返回有服务区但没有位置的地方的评论?