【问题标题】:Parallel computing in Python Similar to MATLABPython中的并行计算类似于MATLAB
【发布时间】:2022-07-06 02:18:39
【问题描述】:

我在 MATLAB 中使用 parfor 来并行运行 for 循环已经有一段时间了。我需要在 Python 中做类似的事情,但我找不到任何简单的解决方案。这是我的代码:

t = list(range(1,3,1))
G = list(range(0,3,2))
results = pandas.DataFrame(columns = ['tau', 'p_value','G','t_i'],index=range(0,len(G)*len(t)))
counter = 0  
for iteration_G in list(range(0,len(G))):
    for iteration_t in list(range(0,len(t))):
        
        matrix_1,matrix_2 = bunch of code


        tau, p_value = scipy.stats.kendalltau(matrix_1, matrix_2)
        results['tau'][counter] = tau
        results['p_value'][counter] = p_value
        results['G'][counter] = G[iteration_G]
        results['t_i'][counter] = G[iteration_t]
        counter = counter + 1

我想在第一个循环中使用 parfor 等效项。

【问题讨论】:

    标签: python python-3.x multithreading multiprocessing python-multiprocessing


    【解决方案1】:

    我不熟悉parfor,但是你可以使用joblib包来并行运行函数。

    在这个简单的示例中,有一个函数打印其参数,我们使用Parallel 与 for 循环并行执行多次

    import multiprocessing
    from joblib import Parallel, delayed
    
    
    # function that you want to run in parallel
    def foo(i):
        print(i)
    
    
    # define the number of cores (this is how many processes wil run)
    num_cores = multiprocessing.cpu_count()
    
    # execute the function in parallel - `return_list` is a list of the results of the function
    # in this case it will just be a list of None's
    return_list = Parallel(n_jobs=num_cores)(delayed(foo)(i) for i in range(20))
    

    如果这不适用于您想要做的事情,您可以尝试使用 numba - 设置可能有点困难,但理论上使用 numba 您可以添加 @njit(parallel=True) 为您的函数的装饰器,numba 将尝试为您并行化它。

    【讨论】:

      猜你喜欢
      • 2015-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 2014-09-02
      • 1970-01-01
      相关资源
      最近更新 更多