为什么python中的多处理进程较慢
Hei我正在尝试在一个进程上串行运行一个程序,然后在4个进程上使用python中的multiprocessing.process。使用本模块的目的是加速我的程序,以便与学校的项目进行比较。 我不明白为什么我在多处理版本上速度变慢了 这是我要以串行方式运行的代码:为什么python中的多处理进程较慢,python,python-multiprocessing,Python,Python Multiprocessing,Hei我正在尝试在一个进程上串行运行一个程序,然后在4个进程上使用python中的multiprocessing.process。使用本模块的目的是加速我的程序,以便与学校的项目进行比较。 我不明白为什么我在多处理版本上速度变慢了 这是我要以串行方式运行的代码: import os print('Implementing Matrix multiplication serial on one process \n') A = [[1,1,1,1], [2,2,2,2], [3
import os
print('Implementing Matrix multiplication serial on one process \n')
A = [[1,1,1,1],
[2,2,2,2],
[3,3,3,3],
[3,3,3,3]]
B = [[1,1,1,1],
[2,2,2,2],
[3,3,3,3],
[3,3,3,3]]
for x in range(4):
def matrixMul(A,B):
for i in range(4):
for j in range(4):
for k in range(4):
result[i][j] += A[i][k] * B[k][j]
for r in result:
print(r)
process_id=os.getpid()
print ("The process ID:",process_id)
result = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
matrixMul(A,B)
以下是使用多进程时的注意事项:
import os
import multiprocessing
print('Implementing Matrix multiplication parallely on 4
processes \n')
A = [[1,1,1,1],
[2,2,2,2],
[3,3,3,3],
[3,3,3,3]]
B = [[1,1,1,1],
[2,2,2,2],
[3,3,3,3],
[3,3,3,3]]
def matrixMul(A,B):
for i in range(4):
for j in range(4):
for k in range(4):
result[i][j] += A[i][k] * B[k][j]
for r in result:
print(r)
process_id=os.getpid()
print ("The process ID:",process_id)
result = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
jobs = []
for x in range(4):
p = multiprocessing.Process(target=matrixMul, args=(A,B))
p.start()
jobs.append(p)
for proc in jobs:
proc.join()
请帮我弄清楚答案,因为我是python的初学者
结果如下:
[9, 9, 9, 9]
[18, 18, 18, 18]
[27, 27, 27, 27]
[27, 27, 27, 27]
The process ID: 22509
[9, 9, 9, 9]
[18, 18, 18, 18]
[27, 27, 27, 27]
[27, 27, 27, 27]
The process ID: 22509
[9, 9, 9, 9]
[18, 18, 18, 18]
[27, 27, 27, 27]
[27, 27, 27, 27]
The process ID: 22509
[9, 9, 9, 9]
[18, 18, 18, 18]
[27, 27, 27, 27]
[27, 27, 27, 27]
The process ID: 22509
real 0m0,022s
user 0m0,018s
sys 0m0,004s
并从多个一的结果:
[9, 9, 9, 9]
[18, 18, 18, 18]
[27, 27, 27, 27]
[27, 27, 27, 27]
The process ID: 22511
[9, 9, 9, 9]
[18, 18, 18, 18]
[27, 27, 27, 27]
[27, 27, 27, 27]
The process ID: 22512
[9, 9, 9, 9]
[18, 18, 18, 18]
[27, 27, 27, 27]
[27, 27, 27, 27]
The process ID: 22513
[9, 9, 9, 9]
[18, 18, 18, 18]
[27, 27, 27, 27]
[27, 27, 27, 27]
The process ID: 22514
real 0m0,069s
user 0m0,056s
sys 0m0,049s
哪个操作系统?像windows这样的操作系统需要为每个进程创建一个新的python实例,这可能会更慢。考虑到您的代码不使用
if uuuu name_uuu==“uuuu main_uuu”:
来保护自己不在子流程中运行模块级代码,这可能是linux或mac,但最好是显式的。同时计时和发布结果也会很有用,这样我们就可以看到区别了。我在我的linux机器上运行了你的代码,并用了并行和串行。然而,在这两种情况下,运行时间都非常小。占主导地位的时间消费者是状态打印。在进行基准测试时,您应该去掉这些选项。@tdelaney我使用的是linux debian,我已经用if name==“main”尝试过了:也没有变化,再次运行,serlai beat parallel-一定是背景中的其他东西。我认为,由于操作时间很短,分叉的成本是不合理的。以下是结果:[9,9,9,9][18,18,18,18,18][27,27,27,27,27,27,27]流程ID:22509[9,9,9,9][18,18][27,27,27,27][27]流程ID:22509[9,9,9,9][18,18,18][27,27,27][27]27流程ID:22509[9,9,9][18,18,18][27,27,27][27,27,27]流程ID:22509 real 0M0022S user 0M0018S sys 0M0004S