2

Consider the following Pythonic snippet, "timing.py":

import numpy as np

def exponentials(n_, x_):
    n_exp = np.arange(0,n_,1)
    y_exp = np.zeros(n_)
    y_exp[:] = np.exp(-x_*n_exp[:])

def powers(n_, x_):
    n_exp = np.arange(0,n_,1)
    y_exp = np.zeros(n_)
    expbase = np.exp(-x_)
    y_exp = expbase**n_exp

Now consider the following timing result

In [1]: import timing

In [2]: %timeit timing.exponentials(1e3, 1.1)
100000 loops, best of 3: 14 µs per loop

In [3]: %timeit timing.powers(1e3, 1.1)
10000 loops, best of 3: 27.5 µs per loop

I would have expected that evaluating the exponential function once, and then doing polynomials would have been significantly faster than evaluating the exponential function 10^3 times. At best, I expected them to be comparable. Does anybody have any insight in what's going on here?

This is NumPy version 1.9.2 with Python 2.7.10, if that matters.

webb
  • 450
  • 1
  • 3
  • 12
  • Exponentiation using `**` or `np.power` is typically slower than other operations in NumPy; that's what slows the second function down. – Alex Riley Oct 12 '15 at 18:20
  • So what would you suggest in lieu of power functions? Why are the power functions slower than evaluating the exponential (which I would have assumed involved evaluating powers)? – webb Oct 12 '15 at 18:30
  • 2
    Note that n_exp are floating point values, and factional powers are not exactly easy to compute; I am not sure about the precise underlying instructions used, but I can easy see the exp one being more optimized – Eelco Hoogendoorn Oct 12 '15 at 20:06
  • 2
    [Similar questions](http://stackoverflow.com/questions/25254541/why-is-numpy-power-60x-slower-than-in-lining) have come up here in the past. One reason is that, comparison of `**` vs `exp` ultimately boils down to what happens at C and hence at assembly level. Most of today's micro-processors do not have intrinsics for power computation, while they do support `log` and `exp` using predefined tables. – romeric Oct 12 '15 at 20:09
  • So if I wanted this code to be supremely fast, what would people recommend? – webb Oct 12 '15 at 22:40

0 Answers0