【问题标题】:How to use multiprocessing for a for loop? How to make a core run the loop from index n1 to n2 and the other core from index n2 to n3?如何为 for 循环使用多处理?如何让一个核心运行从索引 n1 到 n2 的循环以及从索引 n2 到 n3 的另一个核心?
【发布时间】:2019-08-30 14:29:13
【问题描述】:

我编写了一个代码来将二维高斯的值分配给空的 HEALPix 数组。为此,我在像素索引中创建了一个“for”循环。但是代码似乎要花很多时间才能给出输出。有人可以帮我把这个循环分成几部分,以便同时处理它们吗?以下是我想要多处理的代码部分。

def fn(nside):
    bar = ProgressBar(maxval = npix)
    bar.start()
    for i in range(0,npix):
        bar.update(i)
        for j in range(0,npix):
            hpxmap0[hp.ang2pix(nside, ma_theta[i], ma_phi[j])] = gaussian_2D(np.pi*(0.5) - ma_theta[i], ma_phi[j])
    bar.finish()
    return hpxmap0

【问题讨论】:

    标签: python for-loop multiprocessing healpy


    【解决方案1】:

    编写一个包装函数以在给定的像素范围内运行循环:

    def fn_dist(nside, i_lo, i_hi, j_lo, j_hi):
        ...
        for i in range(i_lo, i_hi):
            for j in range(j_lo, j_hi):
                ...
    

    现在,您需要在所需范围内分叉您的进程,将矩阵分成i_stepj_step 的切片:

    for i_lo in range(0, npix, i_step):
        for j_lo in range(0, npix, j_step):
            # spawn a process for fn(nside, i_lo, i_lo+i_step, j_lo, j_lo+j_step)
    

    还要寻找进行块操作的方法。您能否编写自己的gaussian_2D 函数版本来返回给定范围内的值矩阵?我强烈怀疑您目前的大部分时间都浪费在单值函数调用的开销上,而不是数据传输上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      相关资源
      最近更新 更多