为什么实现多处理会使我的程序变慢



我正试图在代码中实现多处理,以使其更快。

为了更容易理解,我只想说,该程序使用曲线库的线性组合拟合观察到的曲线,并由此测量观察到曲线的特性。

我必须对400多条曲线这样做,为了估计这些特性的误差,我进行了蒙特卡洛模拟,这意味着每次计算都必须迭代多次。

这需要大量的时间和工作,而且我相信这是一项CPU限制的任务,我认为我会在错误估计步骤中使用多处理。以下是我的代码的简化:

无多处理

import numpy as np
import fitting_package
import multiprocessing

def estimate_errors(best_fit_curve, signal_to_noise, fit_kwargs, iterations=100)
results = defaultdict(list)
def fit(best_fit_curve, signal_to_noise, fit_kwargs, results):
# Here noise is added to simulate a new curve (Monte Carlo simulation)
noise = best_fit/signal_to_noise
simulated_curve = np.random.normal(best_fit_curve, noise)
# The arguments from the original fit (outside the error estimation) are passed to the fitting
fit_kwargs.update({'curve' : simulated_curve})
# The fit is performed and it returns the properties packed together
solutions = fitting_package(**fit_kwargs)
# There are more properties so this is a simplification
property_1, property_2 = solutions
aux_dict = {'property_1' : property_1, 'property_2' : property_2}
for key, value in aux_dict.items():
results[key].append(values)
for _ in range(iterations):
fit(best_fit_curve, signal_to_noise, fit_kwargs, results)
return results

具有多处理

def estimate_errors(best_fit_curve, signal_to_noise, fit_kwargs, iterations=100)
def fit(best_fit_curve, signal_to_noise, fit_kwargs, queue):
results = queue.get()
noise = best_fit/signal_to_noise
simulated_curve = np.random.normal(best_fit_curve, noise)
fit_kwargs.update({'curve' : simulated_curve})
solutions = fitting_package(**fit_kwargs)
property_1, property_2 = solutions
aux_dict = {'property_1' : property_1, 'property_2' : property_2}
for key, value in aux_dict.items():
results[key].append(values)
queue.put(results)
process_list = []
queue = multiprocessing.Queue()
queue.put(defaultdict(list))
for _ in range(iterations):
process = multiprocessing.Process(target=fit, args=(best_fit_curve, signal_to_noise, fit_kwargs, queue))
process.start()
process_list.append(process)
for p in process_list:
p.join()
results = queue.get()
return results

我原以为使用多处理可以节省时间,但实际上它比其他方法需要两倍多的时间。为什么会这样?有没有什么办法可以让多处理更快?

我原以为使用多处理可以节省时间,但实际上它比其他方法需要两倍多的时间。为什么会这样?

启动一个进程需要很长时间(至少在计算机方面(。它还占用了大量内存。

在您的代码中,您将在100个独立的操作系统进程中启动100个单独的Python解释器。这需要很长的时间,所以除非每个流程都运行很长时间,否则启动流程所需的时间将主导它实际完成有用工作的时间。

除此之外,除非你真的有100个未使用的CPU内核,否则这100个进程将花费大部分时间等待彼此完成。更糟糕的是,由于它们都有相同的优先级,操作系统会尝试给它们每个人一段相当长的时间,所以它会运行它们一段时间,然后挂起它们,运行其他程序一段时间、挂起它们等等。所有这些调度也需要时间

拥有比并行资源更多的并行工作负载不能加速程序,因为它们无论如何都必须等待一个接一个的执行。

只有当并行任务的时间不受创建、管理、调度和重新加入并行任务时间的支配时,并行性才会加快程序的速度。

最新更新