I would like to perform a million times 10 to the power of a real number (10**x, where x = float) as fast as possible. My fastest option so far was using numpy's exp function:
import numpy as np
n = 1000000
p = np.random.uniform(0.,1.,n)
def pow10(p):
ln10 = np.log(10)
return np.exp(p*ln10)
Which takes on my machine about 6 ms.
Using Cython, performing the power function a million times is about 10 000 times faster (500 ns):
%%cython
import numpy as np
cimport numpy as np
cimport cython
@cython.boundscheck(False)
@cython.wraparound(False)
def cpow10(double[::1] p, int n):
cdef int i
cdef double res
for i in range(n):
res = 10**p[i] # just calculation
return True
result = cpow10(p,n)
BUT only if I don't store the results back in an array:
def cpow10(double[::1] p,double[::1] res, int n):
cdef int i
for i in range(n):
res[i] = 10**p[i] # calculation and storage
return res
r = np.zeros((n),dtype=float)
result = cpow10(p,r,n)
Which yields again about 6 ms. Any idea why I loose so much speed and how to fix this ?