np.array == num 比较很慢吗?可以使用多处理来加速吗?

is np.array == num comparison very slow? Can multiprocessing be used to accelerate it?

大np.array与单号python之间的==比较?我使用 line_profiler 来定位代码中的瓶颈。瓶颈只是 1d np.array 与常数之间的简单比较。它占总运行时间的80%。我做错了什么导致它这么慢吗?有什么办法可以加速吗?

我尝试使用 multiprocessing,但是,在测试代码(片段 2)中,使用 multiprocessing 比按顺序 运行 和直接使用 map 慢。谁能解释这种现象?

如有任何意见或建议,我们将不胜感激。

片段 1:

行 # Hits Time Per Hit %Time Line Contents

38 12635 305767927.0 24200.1 80.0 res = map(logicalEqual,assembly)

def logicalEqual(x):
         return F[:,-1] == x

assembly = [1,2,3,4,5,7,8,9,...,25]

F 是一个 int 类型 (281900, 6) np.array

代码段 2:

import numpy as np
from multiprocessing import Pool
import time

y=np.random.randint(2, 20, size=10000000)

def logicalEqual(x):
    return y == x

p=Pool()
start = time.time()
res0=p.map(logicalEqual, [1,2,3,4,5,7,8,9,10,11,12,13,14,15])
# p.close()
# p.join()
runtime = time.time()-start
print(f'runtime using multiprocessing.Pool is {runtime}')

res1 = []
start = time.time()
for x in [1,2,3,4,5,7,8,9,10,11,12,13,14,15]:
    res1.append(logicalEqual(x))
runtime = time.time()-start
print(f'sequential runtime is {runtime}')


start = time.time()
res2=list(map(logicalEqual,[1,2,3,4,5,7,8,9,10,11,12,13,14,15]))
runtime = time.time()-start
print(f'runtime is {runtime}')

runtime using multiprocessing.Pool is 0.3612203598022461
sequential runtime is 0.17401981353759766
runtime is  0.19697237014770508

数组比较很快,因为它是用 C 代码完成的,而不是 Python。

x = np.random.rand(1000000)
y = 4.5
test = 0.55
%timeit x == test
386 µs ± 4.68 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit y == test
33.2 ns ± 0.121 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

因此,将一个 Python 浮点数与另一个进行比较需要 33*10^-9 秒,而比较 1E6 numpy 浮点数只需要 386 微秒/33 纳秒 ~= 11700 倍的时间,尽管比较了 1000000 个以上的值。整数也是如此(377 µs 对 34 ns)。但是正如沙丘在评论中提到的那样,比较很多值需要很多周期。你对此无能为力。