Skip to content

Instantly share code, notes, and snippets.

@ykm11
Last active January 5, 2023 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ykm11/64584fe1f03c33ff99cc9f48265b26c0 to your computer and use it in GitHub Desktop.
Save ykm11/64584fe1f03c33ff99cc9f48265b26c0 to your computer and use it in GitHub Desktop.
Power functions for numpy.array with only positive-number exponent
import timeit
import numpy as np
from mypower import mypower
def fff(array, d):
y2 = array**d # this calls np.power
return y2
def ggg(array, d):
y2 = np.power(array, d)
return y2
def hhh(array, d):
yd = np.copy(array)
#y2 = array * array * array * array
for _ in range(d-1):
yd *= array
#return y2
return yd
N = 1000
M = 30000
np.random.seed(1)
d = 6
a = np.random.random(M)
#a = np.array([float(i)+0.0 for i in range(M)])
#x = fff(a, d)
#y = mypower(a, d)
#print(x - y)
print("Exponent =", d)
result = timeit.timeit('fff(a, d)', globals=globals(), number=N)
print("array**d:\t\t", result / N)
result = timeit.timeit('ggg(a, d)', globals=globals(), number=N)
print("np.power(array, d):\t", result / N)
result = timeit.timeit('hhh(a, d)', globals=globals(), number=N)
print("Inline power:\t\t", result / N)
result = timeit.timeit('mypower(a,d)', globals=globals(), number=N)
print("YJSP:\t\t\t", result / N)
import numpy as np
cimport numpy as cnp
ctypedef cnp.float64_t DTYPE_t
#ctypedef cnp.float128_t DTYPE_t
cpdef mypower(cnp.ndarray[DTYPE_t, ndim=1] array, long long d):
#assert(type(d) is int)
assert(d > 0)
cdef cnp.ndarray[DTYPE_t, ndim=1] t
cdef int bit_size = d.bit_length()
t = array.copy()
for j in range(bit_size - 1, 0, -1):
t *= t
if (d & (1 << (j-1))):
t *= array
return t
Exponent = 6
array**d: 0.0005299898610101082
np.power(array, d): 0.0005025769440107979
Inline power: 6.187346600927412e-05
YJSP: 3.45221110037528e-05
Exponent = 3
array**d: 0.0005009942409815267
np.power(array, d): 0.0004991821850417182
Inline power: 3.0344719998538495e-05
YJSP: 2.674185700016096e-05
Exponent = 34
array**d: 0.0004983039390062913
np.power(array, d): 0.0004962649489752948
Inline power: 0.0003429475580342114
YJSP: 5.481089395470917e-05
Exponent = 4
array**d: 0.0005093903410015628
np.power(array, d): 0.0005355970499804244
Inline power: 4.0681859012693164e-05
YJSP: 2.4485233006998895e-05
from distutils.core import setup
from Cython.Build import cythonize
import numpy
## python3 setup.py build_ext --inplace
setup(
name = 'mypower',
ext_modules = cythonize('mypower.pyx'),
include_dirs = [numpy.get_include()]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment