NumPy 的数学函数是否比 Python 的快? [英] Are NumPy's math functions faster than Python's?
问题描述
我有一个由基本数学函数(abs、cosh、sinh、exp、...)组合定义的函数.
I have a function defined by a combination of basic math functions (abs, cosh, sinh, exp, ...).
我想知道它是否会在使用上(速度)有所不同,例如,numpy.abs()
而不是 abs()
?
I was wondering if it makes a difference (in speed) to use, for example,
numpy.abs()
instead of abs()
?
推荐答案
以下是时序结果:
lebigot@weinberg ~ % python -m timeit 'abs(3.15)'
10000000 loops, best of 3: 0.146 usec per loop
lebigot@weinberg ~ % python -m timeit -s 'from numpy import abs as nabs' 'nabs(3.15)'
100000 loops, best of 3: 3.92 usec per loop
numpy.abs()
比 abs()
慢,因为它也处理 Numpy 数组:它包含提供这种灵活性的附加代码.
numpy.abs()
is slower than abs()
because it also handles Numpy arrays: it contains additional code that provides this flexibility.
然而,Numpy 在数组上速度很快:
However, Numpy is fast on arrays:
lebigot@weinberg ~ % python -m timeit -s 'a = [3.15]*1000' '[abs(x) for x in a]'
10000 loops, best of 3: 186 usec per loop
lebigot@weinberg ~ % python -m timeit -s 'import numpy; a = numpy.empty(1000); a.fill(3.15)' 'numpy.abs(a)'
100000 loops, best of 3: 6.47 usec per loop
(PS: '[abs(x) for x in a]'
在 Python 2.7 中比更好的 map(abs, a)
慢,大约是快了 30%——这仍然比 NumPy 慢得多.)
(PS: '[abs(x) for x in a]'
is slower in Python 2.7 than the better map(abs, a)
, which is about 30 % faster—which is still much slower than NumPy.)
因此,对于 1000 个元素,numpy.abs()
花费的时间并不比 1 个单浮点数多!
Thus, numpy.abs()
does not take much more time for 1000 elements than for 1 single float!
这篇关于NumPy 的数学函数是否比 Python 的快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!