import os
import numpy as np
import time
from multiprocessing import Process, current_process
def doubler(number):
result = number * 2
proc_name = current_process().name
print('{0} doubled to {1} by: {2}'.format(number, result, proc_name))
def solve_inverse(np_ndarray_square_matrix):
inverse_matrix=np.linalg.inv(np_ndarray_square_matrix)
proc_name = current_process().name
print('process name :',proc_name,' ',inverse_matrix)
if __name__=='__main__':
start_time=time.time()
dim=100
thread_num=10
matrice = [np.random.normal(loc=1.0 , scale=5.0 , size=(dim,dim)) for _ in range(thread_num)]
procs = []
for index, matrix in enumerate(matrice):
proc = Process(target=solve_inverse , args=(matrix,))
procs.append(proc)
proc.start()
for proc in procs:
proc.join()
end_time=time.time()
print('time length :',end_time-start_time)
上面的代码是一个简单的python代码,它用多处理计算随机采样矩阵的逆。但是,下面的代码不起作用这两个简单的python代码有什么不同? (一个工作,另一个不工作)
import os
import numpy as np
import time
from multiprocessing import Process, current_process
def doubler(number):
result = number * 2
proc_name = current_process().name
print('{0} doubled to {1} by: {2}'.format(number, result, proc_name))
def solve_inverse(np_ndarray_square_matrix):
inverse_matrix=np.linalg.inv(np_ndarray_square_matrix)
proc_name = current_process().name
print('process name :',proc_name,' ',inverse_matrix)
start_time=time.time()
dim=3
thread_num=10
matrice = [np.random.normal(loc=1.0 , scale=5.0 , size=(dim,dim)) for _ in range(thread_num)]
procs = []
for index, matrix in enumerate(matrice):
proc = Process(target=solve_inverse , args=(matrix,))
procs.append(proc)
proc.start()
for proc in procs:
proc.join()
end_time=time.time()
print('time length :',end_time-start_time)
,唯一的区别在于是否有if __name__=='__main__:
与否。 据我所知,if __name__=='__main__:
认识到,如果这个模块是由其他模块导入或该模块自己运行。所以我认为实际上两个代码之间没有区别来决定计算机应该做什么。怎么了?
还有一个问题!看起来第一个代码并不是'多处理',我的意思是,当我观察代码从开始到结束的时间时,多处理似乎不能同时工作。当我增加多处理数量时,时间线性增加w.r.t.多处理的数量。我不知道发生了什么!请帮帮我! – Eric
这些答案将有所帮助。 https://stackoverflow.com/a/29697273/4045933, https://stackoverflow.com/a/18205006/4045933 – SunilT