首页 > 解决方案 > 使用 numpy min、max(或 numba)进行 Python 优化

问题描述

我需要用 python 和 numpy 进行性能优化。

我的数据是这样的

a1 = np.array(np.random.random(500000) * 1000)
a2 = np.array(np.random.random(500000) * 5000)

使用不同的 ndarray a1, a2,我想计算 min-max gap。

麻木:

np.max(a1) - np.min(a2)

麻木:

@nb.jit(nb.float64(nb.float64, nb.float64), cache=True, fastmath=True)
def nb_max_min(s1, s2):
    return np.max(s1) - np.min(s2)

但是,我得到了失望的结果

min-max(numba): 1.574092000000249 ms
max-max(numpy): 1.4246419999999205 ms

如果可能的话,我想在 ~0.xx ms 内进行更快速的计算。如何克服这种优化?


更新

我只测量了最大 - 最小部分。我的计时码在这里。

import time


def timing(label, fn):
    t0 = time.perf_counter()
    fn()
    t1 = time.perf_counter()
    print('{}: {} ms'.format(label, (t1 - t0) * 1000))

我所有的代码在这里,

@nb.jit(nb.float64(nb.float64, nb.float64), cache=True, fastmath=True)
def nb_max_min(s1, s2):
    return np.max(s1) - np.min(s2)


a1 = np.random.random(periods) * 2000
a2 = np.random.random(periods) * 1000
timing('nb_min_max', lambda: nb_max_min(a1, a2))
timing('nb_min_max', lambda: nb_max_min(a1, a2))
timing('nb_min_max', lambda: nb_max_min(a1, a2))
timing('max-max', lambda: np.max(a1) - np.min(a2))
timing('max-max', lambda: np.max(a1) - np.min(a2))
timing('max-max', lambda: np.max(a1) - np.min(a2))

而且,这是结果

nb_min_max: 0.728947999999896 ms
nb_min_max: 1.0030130000000526 ms
nb_min_max: 1.3124690000001493 ms
max-max: 1.662436000000156 ms
max-max: 0.9315169999997153 ms
max-max: 1.9570019999992638 ms

我也试过timeit

%timeit np.max(a1) - np.min(a2)

475 µs ± 9.72 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

我认为这是使用 python 最快的方法。Numpy 或 numba 的结果没有显着差异。正如 user2699 评论的那样,fortran 是优化的最后机会。

标签: pythonnumpyoptimizationnumba

解决方案


在 ipython 中使用 '%timeit' 魔法,我得到了以下结果:

数组生成:

%%timeit
a1 = np.array(np.random.random(500000) * 1000)
a2 = np.array(np.random.random(500000) * 5000)
% 23.3 ms

最小-最大间隙:

%%timeit
np.max(a1) - np.min(a2)
% 444 µs

我认为这已经非常快了,也许你测量了一些额外的开销,就像@juvian 建议的那样?


推荐阅读