NumPy的数学函数是否比Python快? [英] Are NumPy's math functions faster than Python's?

查看:126
本文介绍了NumPy的数学函数是否比Python快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由基本数学函数(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.)

因此,numpy.abs()对于1000个元素所花费的时间不会比1个单个浮点所花费的时间多得多!

Thus, numpy.abs() does not take much more time for 1000 elements than for 1 single float!

这篇关于NumPy的数学函数是否比Python快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆