所以如果我有类似 x=np.random.rand(60000)*400-200
的东西. iPython 的 %timeit
说:
-
x.astype(int)
耗时 0.14 毫秒 -
np.rint(x)
和np.around(x)
耗时 1.01 毫秒
请注意,在 rint
中和 around
情况下你仍然需要花费额外的 0.14ms 来做最后的 astype(int)
(假设这是您最终想要的)。
问题:我认为大多数现代硬件能够同时执行这两项操作是否正确?如果是这样,为什么 numpy 的舍入时间要长 8 倍?
碰巧我对算术的准确性不是很挑剔,但我看不出如何利用 numpy 来利用它(我正在研究困惑的生物学而不是粒子物理学)。
最佳答案
np.around(x).astype(int)
和 x.astype(int)
不要产生相同的值。前者四舍五入(与 ((x*x>=0+0.5) + (x*x<0-0.5)).astype(int)
相同),而后者四舍五入为零。然而,
y = np.trunc(x).astype(int)
z = x.astype(int)
显示y==z
但正在计算 y
慢得多。所以它是 np.trunc
和 np.around
慢的函数。
In [165]: x.dtype
Out[165]: dtype('float64')
In [168]: y.dtype
Out[168]: dtype('int64')
所以 np.trunc(x)
从 double 到 double 向零舍入。然后 astype(int)
必须将 double 转换为 int64。
在内部我不知道 python 或 numpy 在做什么,但我知道我将如何在 C 中执行此操作。让我们讨论一些硬件。使用 SSE4.1 可以使用 round、floor、ceil 和 trunc 从 double 到 double 使用:
_mm_round_pd(a, 0); //round: round even
_mm_round_pd(a, 1); //floor: round towards minus infinity
_mm_round_pd(a, 2); //ceil: round towards positive infinity
_mm_round_pd(a, 3); //trunc: round towards zero
但 numpy 也需要支持没有 SSE4.1 的系统,因此它必须在没有 SSE4.1 和 SSE4.1 的情况下构建,然后使用调度程序。
但是在 AVX512 之前,使用 SSE/AVX 将 double 直接转换为 int64 并不高效。但是,仅使用 SSE2 就可以有效地将 double 舍入为 int32:
_mm_cvtpd_epi32(a); //round double to int32 then expand to int64
_mm_cvttpd_epi32(a); //trunc double to int32 then expand to int64
这些将两个 double 转换为两个 int64。
在您的情况下,这会很好地工作,因为范围肯定在 int32 范围内。但是,除非 python 知道范围适合 int32,否则它不能假设这一点,因此它必须四舍五入或截断到 int64,这很慢。此外,无论如何,numpy 都必须构建以支持 SSE2 才能执行此操作。
但也许您可以使用单个 float 组开始。在那种情况下你可以这样做:
_mm_cvtps_epi32(a); //round single to int32
_mm_cvttps_epi32(a) //trunc single to int32
这些将四个单打转换为四个 int32。
因此,为了回答您的问题,SSE2 可以有效地将 double 舍入或截断为 int32。 AVX512 也可以使用 _mm512_cvtpd_epi64(a)
有效地将 double 舍入或截断为 int64。或 _mm512_cvttpd_epi64(a)
. SSE4.1 可以高效地将 float /截断/地板/天花板从 float 到 float 或加倍到加倍。
关于python - 与 astype(int) 相比,numpy around/rint 慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27252209/