4
In [3]: f1 = rand(100000)
In [5]: f2 = rand(100000)

# Obvious method:
In [12]: timeit fmin = np.amin((f1, f2), axis=0); fmax = np.amax((f1, f2), axis=0)
10 loops, best of 3: 59.2 ms per loop

In [13]: timeit fmin, fmax = np.sort((f1, f2), axis=0)
10 loops, best of 3: 30.8 ms per loop

In [14]: timeit fmin = np.where(f2 < f1, f2, f1); fmax = np.where(f2 < f1, f1, f2)
100 loops, best of 3: 5.73 ms per loop


In [36]: f1 = rand(1000,100,100)

In [37]: f2 = rand(1000,100,100)

In [39]: timeit fmin = np.amin((f1, f2), axis=0); fmax = np.amax((f1, f2), axis=0)
1 loops, best of 3: 6.13 s per loop

In [40]: timeit fmin, fmax = np.sort((f1, f2), axis=0)
1 loops, best of 3: 3.3 s per loop

In [41]: timeit fmin = np.where(f2 < f1, f2, f1); fmax = np.where(f2 < f1, f1, f2)
1 loops, best of 3: 617 ms per loop

Like, maybe there's a way to do both where commands in one step with 2 returns?

Why isn't amin implemented the same way as where, if it's so much faster?

4

1 回答 1

5

使用 numpy 内置的元素,maximum并且minimum- 它们比where. numpy 文档中最大的注释证实了这一点:

等效于 np.where(x1 > x2, x1, x2),但速度更快,并且可以进行正确的广播。

您第一次测试所需的行将类似于:

fmin = np.minimum(f1, f2); fmax = np.maximum(f1, f2)

我自己的结果表明这要快得多。请注意,只要两个参数的形状相同, minimumand将适用于任何 n 维数组。maximum

Using amax                    3.506
Using sort                    1.830
Using where                   0.635
Using numpy maximum, minimum  0.178
于 2013-05-16T03:17:59.917 回答