np.exp比np.e慢得多?

时间:2015-05-04 01:41:39

标签: python numpy optimization

In [49]: timeit.timeit("np.exp(100)", setup="import numpy as np")
Out[49]: 1.700455904006958

In [50]: timeit.timeit("np.e**100", setup="import numpy as np")
Out[50]: 0.16629505157470703

有没有理由使用np.e ** 100的CPython实现比使用numpy版本慢得多? numpy版本是否应该更快,因为它被推送到C代码?

2 个答案:

答案 0 :(得分:4)

一个显而易见的原因是np.exp被设置为处理数组,并且在确定输入的类型/维度方面可能存在一些开销。尝试这样的案例,你可能会看到差异减少或消失:

timeit.timeit("np.exp(x)", 
              setup="import numpy as np; x = np.array([99, 100, 101])")
# This actually seems to be faster than just calculating
#   it for a single value
Out[7]: 1.0747020244598389

timeit.timeit("[np.e**n for n in x]", 
              setup="import numpy as np; x = [99, 100, 101]")
Out[8]: 0.7991611957550049

答案 1 :(得分:0)

必须是函数调用开销等。即使np.exp(0)同样很慢,也不应该实际计算任何东西。

>>> timeit.timeit("np.exp(100)", setup="import numpy as np")
2.8452274883430846
>>> timeit.timeit("np.exp(0)", setup="import numpy as np")
2.836107299807054