【问题标题】:Improving matrix operations time using multiprocessing使用多处理改进矩阵运算时间
【发布时间】:2018-10-30 14:24:57
【问题描述】:

有一个 2d numpy 数组,我正在执行以下操作:

rows_count = matrix.shape[0]
mr = []
for i in range(0, rows_count-1):
    for j in range(i+1, rows_count):
        mr.append(matrix[i,:] ^ matrix[j:])

这正是我想要的,但对于大型输入数组来说太慢了。这就是为什么我想使用multiprocessing 来加速我的代码:

import multiprocessing as mp
import numpy as np

pool = mp.Pool(mp.cpu_count())
mr = pool.map(np.bitwise_xor,[(matrix[i,:],matrix[j,:]) for i in range(0, rows_count-1) for j in range(i+1, rows_count)])
pool.join()
pool.close()

但是,此代码的运行速度要慢几倍。如何正确使用multiprocessing(或其他概念)来加速我的代码?

【问题讨论】:

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


【解决方案1】:

结帐时间!

您的新代码将如下所示

from numba import jit

@jit(parallel=True) #yes this decorator and flag is all it takes to run the function in parallel
def my_time_cosuming_thing(mr=[],matrix=np.array(), rows_count=matrix.shape[0])

    for i in range(0, rows_count-1):
      for j in range(i+1, rows_count):
        mr.append(matrix[i,:] ^ matrix[j:])

    return mr

Numba 旨在通过尝试使它们并行运行来使 python 循环超级高效,请在 http://numba.pydata.org/ 上查看它

它还与 numpy 兼容,因此这应该会显着加快您的代码速度,它就像魔术一样,效果很好,我再也不会在没有它的情况下编写嵌套循环了

【讨论】:

  • 不幸的是,这个解决方案似乎也比简单的 for 循环慢。
  • 这很奇怪,很抱歉看起来像是一个插件,但here 是我实现这个的一个项目,如果没有 numba,它根本无法工作,也许尝试复制它?您可以尝试注释掉@jit 行,然后看到它停止运行
猜你喜欢
  • 1970-01-01
  • 2015-08-01
  • 1970-01-01
  • 2019-06-02
  • 2014-04-03
  • 2015-06-25
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
相关资源
最近更新 更多