python - 使用numpy在for循环中进行多核处理

标签 python numpy multicore

我使用 numpy 计算向量。 如何使用多核和 numpy 计算矢量?

import numpy as np

num_row, num_col = 6000, 13572

ss = np.ones((num_row, num_col), dtype=np.complex128)
ph = np.random.standard_normal(num_row)
fre = np.random.standard_normal(num_row)
tau = np.random.standard_normal(num_col)

for idx in range(num_row):
    ss[idx, :] *= np.exp(1j*(ph[idx] + fre[idx]*tau))

最佳答案

我们可以利用 broadcasting拥有基于 NumPy 的解决方案 -

ss = np.exp(1j*(ph[:,None] + fre[:,None]*tau))

将其移植到 numexpr快速利用 transcendental operations alongwith multi-core capability -

import numexpr as ne

def numexpr_soln(ph, fre):
    ph2D = ph[:,None]
    fre2D = fre[:,None]
    return ne.evaluate('exp(1j*(ph2D + fre2D*tau))')

时间 -

In [23]: num_row, num_col = 6000, 13572
    ...: ss = np.ones((num_row, num_col), dtype=np.complex128)
    ...: ph = np.random.standard_normal(num_row)
    ...: fre = np.random.standard_normal(num_row)
    ...: tau = np.random.standard_normal(num_col)

# Original soln
In [25]: %%timeit
    ...: for idx in range(num_row):
    ...:     ss[idx, :] *= np.exp(1j*(ph[idx] + fre[idx]*tau))
1 loop, best of 3: 4.46 s per loop

# Native NumPy broadcasting soln
In [26]: %timeit np.exp(1j*(ph[:,None] + fre[:,None]*tau))
1 loop, best of 3: 4.58 s per loop

对于具有不同数量内核/线程的 Numexpr 解决方案 -

# Numexpr solution with # of threads = 2
In [51]: ne.set_num_threads(nthreads=2)
Out[51]: 2

In [52]: %timeit numexpr_soln(ph, fre)
1 loop, best of 3: 2.18 s per loop

# Numexpr solution with # of threads = 4
In [45]: ne.set_num_threads(nthreads=4)
Out[45]: 4

In [46]: %timeit numexpr_soln(ph, fre)
1 loop, best of 3: 1.62 s per loop

# Numexpr solution with # of threads = 8
In [48]: ne.set_num_threads(nthreads=8)
Out[48]: 8

In [49]: %timeit numexpr_soln(ph, fre)
1 loop, best of 3: 898 ms per loop

关于python - 使用numpy在for循环中进行多核处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49901756/

相关文章:

python - 函数似乎返回多个结果或 : what is implicit tuple unpacking

python - SQLAlchemy 唯一对象

python - 在 Django 中模拟瑞士锦标赛

python - Numpy reshape "reversal"

python - Numpy:如何基于子矩阵 B 返回矩阵 A 的 View

python - SCIPY 线性规划方案中缩放矩阵变量的最佳方法

parallel-processing - 在 UMA 机器上使用 MPI 的优势

python - pip 不存在或无法在 virtualenv 中执行

android - 如何在android上获取每个cpu核心的使用情况

.net - Stopwatch.GetTimestamp() 替代方案在多个处理器上是安全的